Python flask.make_response() Examples

The following are code examples for showing how to use flask.make_response(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: basic.py    Apache License 2.0 11 votes vote down vote up
def test_make_response_with_response_instance(self):
        app = flask.Flask(__name__)
        with app.test_request_context():
            rv = flask.make_response(
                flask.jsonify({'msg': 'W00t'}), 400)
            self.assertEqual(rv.status_code, 400)
            self.assertEqual(rv.data, b'{\n  "msg": "W00t"\n}')
            self.assertEqual(rv.mimetype, 'application/json')

            rv = flask.make_response(
                flask.Response(''), 400)
            self.assertEqual(rv.status_code, 400)
            self.assertEqual(rv.data, b'')
            self.assertEqual(rv.mimetype, 'text/html')

            rv = flask.make_response(
                flask.Response('', headers={'Content-Type': 'text/html'}),
                400, [('X-Foo', 'bar')])
            self.assertEqual(rv.status_code, 400)
            self.assertEqual(rv.headers['Content-Type'], 'text/html')
            self.assertEqual(rv.headers['X-Foo'], 'bar') 
Example 2
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: views.py    Apache License 2.0 6 votes vote down vote up
def test_view_decorators(self):
        app = flask.Flask(__name__)

        def add_x_parachute(f):
            def new_function(*args, **kwargs):
                resp = flask.make_response(f(*args, **kwargs))
                resp.headers['X-Parachute'] = 'awesome'
                return resp
            return new_function

        class Index(flask.views.View):
            decorators = [add_x_parachute]
            def dispatch_request(self):
                return 'Awesome'

        app.add_url_rule('/', view_func=Index.as_view('index'))
        c = app.test_client()
        rv = c.get('/')
        self.assert_equal(rv.headers['X-Parachute'], 'awesome')
        self.assert_equal(rv.data, b'Awesome') 
Example 3
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: basic.py    Apache License 2.0 6 votes vote down vote up
def test_make_response(self):
        app = flask.Flask(__name__)
        with app.test_request_context():
            rv = flask.make_response()
            self.assert_equal(rv.status_code, 200)
            self.assert_equal(rv.data, b'')
            self.assert_equal(rv.mimetype, 'text/html')

            rv = flask.make_response('Awesome')
            self.assert_equal(rv.status_code, 200)
            self.assert_equal(rv.data, b'Awesome')
            self.assert_equal(rv.mimetype, 'text/html')

            rv = flask.make_response('W00t', 404)
            self.assert_equal(rv.status_code, 404)
            self.assert_equal(rv.data, b'W00t')
            self.assert_equal(rv.mimetype, 'text/html') 
Example 4
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: views.py    Apache License 2.0 6 votes vote down vote up
def test_view_decorators(self):
        app = flask.Flask(__name__)

        def add_x_parachute(f):
            def new_function(*args, **kwargs):
                resp = flask.make_response(f(*args, **kwargs))
                resp.headers['X-Parachute'] = 'awesome'
                return resp
            return new_function

        class Index(flask.views.View):
            decorators = [add_x_parachute]
            def dispatch_request(self):
                return 'Awesome'

        app.add_url_rule('/', view_func=Index.as_view('index'))
        c = app.test_client()
        rv = c.get('/')
        self.assert_equal(rv.headers['X-Parachute'], 'awesome')
        self.assert_equal(rv.data, b'Awesome') 
Example 5
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: basic.py    Apache License 2.0 6 votes vote down vote up
def test_make_response(self):
        app = flask.Flask(__name__)
        with app.test_request_context():
            rv = flask.make_response()
            self.assert_equal(rv.status_code, 200)
            self.assert_equal(rv.data, b'')
            self.assert_equal(rv.mimetype, 'text/html')

            rv = flask.make_response('Awesome')
            self.assert_equal(rv.status_code, 200)
            self.assert_equal(rv.data, b'Awesome')
            self.assert_equal(rv.mimetype, 'text/html')

            rv = flask.make_response('W00t', 404)
            self.assert_equal(rv.status_code, 404)
            self.assert_equal(rv.data, b'W00t')
            self.assert_equal(rv.mimetype, 'text/html') 
Example 6
Project: flasky   Author: RoseOu   File: views.py    MIT License 6 votes vote down vote up
def test_view_decorators(self):
        app = flask.Flask(__name__)

        def add_x_parachute(f):
            def new_function(*args, **kwargs):
                resp = flask.make_response(f(*args, **kwargs))
                resp.headers['X-Parachute'] = 'awesome'
                return resp
            return new_function

        class Index(flask.views.View):
            decorators = [add_x_parachute]
            def dispatch_request(self):
                return 'Awesome'

        app.add_url_rule('/', view_func=Index.as_view('index'))
        c = app.test_client()
        rv = c.get('/')
        self.assert_equal(rv.headers['X-Parachute'], 'awesome')
        self.assert_equal(rv.data, b'Awesome') 
Example 7
Project: flasky   Author: RoseOu   File: basic.py    MIT License 6 votes vote down vote up
def test_make_response(self):
        app = flask.Flask(__name__)
        with app.test_request_context():
            rv = flask.make_response()
            self.assert_equal(rv.status_code, 200)
            self.assert_equal(rv.data, b'')
            self.assert_equal(rv.mimetype, 'text/html')

            rv = flask.make_response('Awesome')
            self.assert_equal(rv.status_code, 200)
            self.assert_equal(rv.data, b'Awesome')
            self.assert_equal(rv.mimetype, 'text/html')

            rv = flask.make_response('W00t', 404)
            self.assert_equal(rv.status_code, 404)
            self.assert_equal(rv.data, b'W00t')
            self.assert_equal(rv.mimetype, 'text/html') 
Example 8
Project: flasky   Author: RoseOu   File: basic.py    MIT License 6 votes vote down vote up
def test_make_response_with_response_instance(self):
        app = flask.Flask(__name__)
        with app.test_request_context():
            rv = flask.make_response(
                flask.jsonify({'msg': 'W00t'}), 400)
            self.assertEqual(rv.status_code, 400)
            self.assertEqual(rv.data, b'{\n  "msg": "W00t"\n}')
            self.assertEqual(rv.mimetype, 'application/json')

            rv = flask.make_response(
                flask.Response(''), 400)
            self.assertEqual(rv.status_code, 400)
            self.assertEqual(rv.data, b'')
            self.assertEqual(rv.mimetype, 'text/html')

            rv = flask.make_response(
                flask.Response('', headers={'Content-Type': 'text/html'}),
                400, [('X-Foo', 'bar')])
            self.assertEqual(rv.status_code, 400)
            self.assertEqual(rv.headers['Content-Type'], 'text/html')
            self.assertEqual(rv.headers['X-Foo'], 'bar') 
Example 9
Project: flask-observability   Author: adimian   File: test_extension.py    MIT License 6 votes vote down vote up
def app():
    app = Flask("demo")
    app.config["TESTING"] = True
    app.config["OBSERVE_AUTO_BIND_VIEWS"] = True
    obs = Observability(hostname="somehost")
    obs.init_app(app)

    @app.route("/login", methods=["GET"])
    def login_handler():
        if request.form.get("username") == "bad":
            abort(403)
        return make_response("", 200)

    @app.route("/error", methods=["GET"])
    def error():
        errorcode = request.form.get("errorcode")
        if errorcode is not None:
            abort(int(errorcode))
        return make_response("", 200)

    with app.app_context():
        yield app 
Example 10
Project: openvsd   Author: Numergy   File: vsd_mock.py    Apache License 2.0 6 votes vote down vote up
def me_show():
    xrest = [
        "XREST dGVzdDp0ZXN0",         # test/test
        "XREST ZGF0ZTp0ZXN0",         # date/test
        "XREST bnVsbGRhdGU6dGVzdA=="  # nulldate/test
    ]
    auth = request.headers.get('Authorization')
    if not auth in xrest:
        return make_response("<html><head><title>JBoss - Error report</head></html>", '401')
    reply = [{
        'firstName': 'csproot',
        'enterpriseName': 'CSP',
        'APIKey': '02a99c64-a09a-46d7',
        'APIKeyExpiry': (int(epoch()) + 100) * 1000,
        'enterpriseID': 'fc3a351e-87dc-46a4-bcf5-8c4bb204bd46',
    }]
    if auth == "XREST ZGF0ZTp0ZXN0":
        reply[0]['DateDecodeDate'] = '1469448000000'
        reply[0]['DateNotDecode'] = '1469448000000'
        reply[0]['ExpiryDecodeExpiry'] = '1469448000000'

    if auth == "XREST bnVsbGRhdGU6dGVzdA==":
        reply[0]['DateDecodeDate'] = 'null'

    return json.dumps(reply) 
Example 11
Project: openvsd   Author: Numergy   File: vsd_mock.py    Apache License 2.0 6 votes vote down vote up
def license_create():
    data_update = json.loads(request.data)
    if 'licenses' not in database:
        database.update({'licenses': []})
    data_src = get_object_id('licenses', 'license', data_update['license'])
    if data_src != {}:
        return make_response(json.dumps(
            get_object_id('messages', 'name', 'already exists')['message']), '409')
    new = {'license': data_update['license'],
           'ID': '255d9673-7281-43c4-be57-fdec677f6e07',
           'isClusterLicense': 'True',
           'description': 'None',
           'company': 'Compagny-1',
           'allowedNICsCount': '100',
           'allowedVMsCount': '100',
           'productVersion': '2',
           'majorRelease': '6',
           'expirationDate': 1500000000000}
    database['licenses'].append(new)
    return json.dumps([get_object_id('licenses', 'ID', '255d9673-7281-43c4-be57-fdec677f6e07')]) 
Example 12
Project: openvsd   Author: Numergy   File: vsd_mock.py    Apache License 2.0 6 votes vote down vote up
def object_create_with_parent(parent_name, parent_id, obj_name):
    data_update = json.loads(request.data)
    # Check parent exist but don't check parent own objects
    data_src = get_object_id(parent_name, 'ID', parent_id)
    if data_src == {}:
        return make_response(json.dumps(
            get_object_id('messages', 'name', 'not found')['message']), '404')
    if 'name' in data_update.keys():
        data_src = get_object_id(obj_name, 'name', data_update['name'])
        if data_src != {}:
            return make_response(json.dumps(
                get_object_id('messages', 'name', 'already exists')['message']), '409')
    uuid = '255d9673-7281-43c4-be57-fdec677f6e07'
    with_random_uuid = ['dhcpoptions']
    if obj_name in with_random_uuid:
        import uuid
        uuid = str(uuid.uuid4())
    data_update.update({
        'ID': uuid,
        'description': 'None'
    })
    if obj_name not in database:
        database.update({obj_name: []})
    database[obj_name].append(data_update)
    return json.dumps([get_object_id(obj_name, 'ID', uuid)]) 
Example 13
Project: lc3ctf   Author: emc2314   File: server.py    MIT License 6 votes vote down vote up
def task(cat, task_id):
    """Display task"""

    login, user = get_user()
    active = default_active.copy()
    active['tasks'] = 'active'

    task = get_task(task_id)
    if not task:
        return redirect(url_for('error', msg='task_not_found'))

    flags = get_flags()
    task_done = task['id'] in flags

    db = dataset.connect(dbfile)
    solutions = db['flags'].find(task_id=task['id'])
    solutions = len(list(solutions))
    db.executable.close()

    # Render template
    render = render_template('frame.html', lang=lang, page='task.html',
                             task_done=task_done, login=login, solutions=solutions,
                             user=user, category=cat, task=task, score=task['score'], active=active)
    return make_response(render) 
Example 14
Project: lc3ctf   Author: emc2314   File: server.py    MIT License 6 votes vote down vote up
def scoreboard():
    """Displays the scoreboard"""

    active = default_active.copy()
    active['scoreboard'] = 'active'
    db = dataset.connect(dbfile)
    login, user = get_user()
    scores = db.query('''select u.username, ifnull(sum(f.score), 0) as score,
        max(timestamp) as last_submit from users u left join flags f
        on u.id = f.user_id where u.hidden = 0 group by u.username
        order by score desc, last_submit asc''')

    scores = list(scores)
    db.executable.close()

    # Render template
    render = render_template('frame.html', lang=lang, page='scoreboard.html',
                             login=login, user=user, scores=scores, active=active)
    return make_response(render) 
Example 15
Project: TimeplanSoup   Author: Piees   File: main.py    GNU General Public License v3.0 6 votes vote down vote up
def home():
    global nextLectureVar
    global selected
    selected = stringToDict(request.cookies.get('cookieCourse'))
    updateCourses()
    if request.method == 'POST':
        resp = make_response(redirect(url_for('home')))
        if len(request.form['activeCourses']) > 0:
            global selected
            selected = []
            resp.set_cookie('cookieCourse', request.form['activeCourses'] + '|' + request.form['activeCourses2'] + '|' + request.form['activeCourses3'] + '|' + request.form['activeCourses4'] + '|')
            selected.append(request.form['activeCourses'])
        updateCourses()
        return resp
    if request.method == 'GET':
        global selected
        selected = stringToDict(request.cookies.get('cookieCourse'))
        updateCourses()
    nextLectureVar = nextLecture()
    return render_template('main.html', selCourses=selCourses, nextLecture = nextLectureVar, selected = request.cookies.get('cookieCourse')) 
Example 16
Project: beavy   Author: beavyHQ   File: __init__.py    Mozilla Public License 2.0 6 votes vote down vote up
def api_only(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        accepted = set(request.accept_mimetypes.values())
        explicit = not(not request.args.get("json", False))
        if not (accepted & API_MIMETYPES) and not explicit:
            return abort(415, "Unsupported Media Type")

        resp = fn(*args, **kwargs)
        if not isinstance(resp, ResponseBase):
            data, code, headers = unpack(resp)
            # we've found one, return json
            if isinstance(data, MarshalResult):
                data = data.data
            resp = make_response(json.dumps(data,
                                            indent=explicit and 4 or 0),
                                 code)

            if headers:
                resp.headers.update(headers)
            resp.headers["Content-Type"] = 'application/json'
        return resp
    return wrapped 
Example 17
Project: Flask_Blog   Author: sugarguo   File: views.py    GNU General Public License v3.0 6 votes vote down vote up
def test_view_decorators(self):
        app = flask.Flask(__name__)

        def add_x_parachute(f):
            def new_function(*args, **kwargs):
                resp = flask.make_response(f(*args, **kwargs))
                resp.headers['X-Parachute'] = 'awesome'
                return resp
            return new_function

        class Index(flask.views.View):
            decorators = [add_x_parachute]
            def dispatch_request(self):
                return 'Awesome'

        app.add_url_rule('/', view_func=Index.as_view('index'))
        c = app.test_client()
        rv = c.get('/')
        self.assert_equal(rv.headers['X-Parachute'], 'awesome')
        self.assert_equal(rv.data, b'Awesome') 
Example 18
Project: BASS   Author: Cisco-Talos   File: server.py    GNU General Public License v2.0 5 votes vote down vote up
def job_create():
    try:
        job = bass.create_job()
        return jsonify(message = "ok", job = job.json())
    except Exception as ex:
        return make_response(jsonify(message = str(ex), trace = traceback.format_exc()), 400) 
Example 19
Project: BASS   Author: Cisco-Talos   File: server.py    GNU General Public License v2.0 5 votes vote down vote up
def job_get_status(job_id):
    try:
        return jsonify(message = "ok", job = bass.get_job(job_id).json())
    except KeyError:
        return make_response(jsonify(message = "Invalid job id"), 400)
    except Exception as ex:
        return make_response(jsonify(message = str(ex), trace = traceback.format_exc()), 400) 
Example 20
Project: BASS   Author: Cisco-Talos   File: server.py    GNU General Public License v2.0 5 votes vote down vote up
def job_add_sample(job_id):
    try:
        samples = []
        for name, file_ in request.files.items():
            handle, filename = tempfile.mkstemp()
            os.close(handle)
            file_.save(filename)
            samples.append(bass.get_job(job_id).add_sample(filename, name))
        return jsonify(message = "ok", samples = [s.json() for s in samples])
    except KeyError:
        log.exception("Invalid job id")
        return make_response(jsonify(message = "Invalid job id"), 400) 
Example 21
Project: BASS   Author: Cisco-Talos   File: server.py    GNU General Public License v2.0 5 votes vote down vote up
def job_submit(job_id):
    try:
        bass.submit_job(job_id)
        return jsonify(message = "ok")
    except KeyError:
        return make_response(jsonify(message = "Invalid job id"), 400) 
Example 22
Project: BASS   Author: Cisco-Talos   File: server.py    GNU General Public License v2.0 5 votes vote down vote up
def job_delete(job_id):
    try:
        bass.delete_job(job_id)
        return jsonify(message = "ok")
    except KeyError:
        return make_response(jsonify(message = "Invalid job id"), 400) 
Example 23
Project: BASS   Author: Cisco-Talos   File: server.py    GNU General Public License v2.0 5 votes vote down vote up
def function_get(fid):
    global Session
    session = Session()
    try:
        function = session.query(Function).filter(Function.id == fid).one()
        return make_response(jsonify(**json.loads(function.data)), 200)
    except NoResultFound:
        return make_response(jsonify(message = "Function not found"), 404) 
Example 24
Project: BASS   Author: Cisco-Talos   File: server.py    GNU General Public License v2.0 5 votes vote down vote up
def function_raw_hash_get():
    global Session
    session = Session()
    filename, file_ = request.files.items()[0]
    db = Database(pickle.load(file_))

    arch_name = db.architecture_name
    if arch_name == "metapc":
        arch_name = "x86"
    try:
        arch = session.query(Architecture).filter(Architecture.name == arch_name and \
                Architecture.bits == db.architecture_bits and \
                Architecture.little_endian == db.architecture_endianness == "little").one()
    except NoResultFound:
        return make_response(jsonify(message = "Architecture not found"), 404)
    
    try:
        func = next(db.functions)
    except StopIteration:
        return make_response(jsonify(message = "No function found in database"), 500)

    raw_hash = _function_calculate_raw_sha256(func)
    size = _function_get_size(func)

    try:
        function = session.query(Function).filter(Function.raw_sha256 == raw_hash and \
                Function.size == size and \
                Function.arch == arch.id).one()
        return make_response(jsonify(**json.loads(function.data)), 200)
    except NoResultFound:
        return make_response(jsonify(message = "Function not found"), 404) 
Example 25
Project: BASS   Author: Cisco-Talos   File: server.py    GNU General Public License v2.0 5 votes vote down vote up
def function_mnem_hash_get():
    global Session
    session = Session()
    filename, file_ = request.files.items()[0]
    db = Database(pickle.load(file_))

    arch_name = db.architecture_name
    if arch_name == "metapc":
        arch_name = "x86"
    try:
        arch = session.query(Architecture).filter(Architecture.name == arch_name and \
                Architecture.bits == db.architecture_bits and \
                Architecture.little_endian == db.architecture_endianness == "little").one()
    except NoResultFound:
        return make_response(jsonify(message = "Architecture not found"), 404)
    
    try:
        func = next(db.functions)
    except StopIteration:
        return make_response(jsonify(message = "No function found in database"), 500)

    mnem_hash = _function_calculate_mnem_sha256(func)

    try:
        function = session.query(Function).filter(Function.mnem_sha256 == mnem_hash and \
                Function.arch == arch.id).one()
        return make_response(jsonify(**json.loads(function.data)), 200)
    except NoResultFound:
        return make_response(jsonify(message = "Function not found"), 404) 
Example 26
Project: BASS   Author: Cisco-Talos   File: ida_service.py    GNU General Public License v2.0 5 votes vote down vote up
def bindiff_export():
    """
    Run the IDA Pro autoanalysis on the input file and export a BinExport database.
    :param input: The input file
    :return: Status code 200 and a JSON object containing the output database
        name in key 'output', or status code 422 on invalid parameters, 408 on
        timeout or 500 on other errors.
    """
    logger.info("bindiff_export called")

    directory = None
    try:
        directory = tempfile.mkdtemp()
        if len(request.files) != 1:
            return make_response(jsonify(error = "Missing file parameter"), 422)

        filename, file_ = request.files.items()[0]
        input_ = os.path.join(directory, sanitize_filename(filename))
        file_.save(input_)

        output = os.path.join(directory, "output.BinExport")

        timeout = request.form.get('timeout', None)
        is_64_bit = request.form.get('is_64_bit', True)
        try:
            run_ida(input_, is_64_bit, timeout, os.path.join(PREFIX, "export_binexport_pickle.py"), "binexport", output)
            logger.info("Command completed successfully")
            return send_file(open(output, "rb"), as_attachment = True, attachment_filename = "%s.BinExport" % filename, mimetype = "application/binary")
        except TimeoutError:
            return jsonify(error = "Program execution timed out"), 408
        except OSError as err:
            return jsonify(error = "Program execution failed with error %d" % err.errno), 500
            
    finally:
        if directory is not None:
            shutil.rmtree(directory) 
Example 27
Project: BASS   Author: Cisco-Talos   File: ida_service.py    GNU General Public License v2.0 5 votes vote down vote up
def pickle_export():
    """
    Run the IDA Pro autoanalysis on the input file and export a BinExport database.
    :param input: The input file
    :return: Status code 200 and a JSON object containing the output database
        name in key 'output', or status code 422 on invalid parameters, 408 on
        timeout or 500 on other errors.
    """
    logger.info("bindiff_export called")

    directory = None
    try:
        directory = tempfile.mkdtemp()
        if len(request.files) != 1:
            return make_response(jsonify(error = "Missing file parameter"), 422)

        filename, file_ = request.files.items()[0]
        input_ = os.path.join(directory, sanitize_filename(filename))
        file_.save(input_)

        output = os.path.join(directory, "output.pickle")

        timeout = request.form.get('timeout', None)
        is_64_bit = request.form.get('is_64_bit', False)
        try:
            run_ida(input_, is_64_bit, timeout, os.path.join(PREFIX, "export_binexport_pickle.py"), "pickle", output)
            logger.info("Command completed successfully")
            return send_file(open(output, "rb"), as_attachment = True, attachment_filename = "%s.pickle" % filename, mimetype = "application/binary")
        except TimeoutError:
            return jsonify(error = "Program execution timed out"), 408
        except OSError as err:
            return jsonify(error = "Program execution failed with error %d" % err.errno), 500
    finally:
        if directory is not None:
            shutil.rmtree(directory) 
Example 28
Project: BASS   Author: Cisco-Talos   File: ida_service.py    GNU General Public License v2.0 5 votes vote down vote up
def bindiff_compare():
    logger.info("bindiff_compare called")

    input_dir = tempfile.mkdtemp()
    output_dir = tempfile.mkdtemp()
    try:
        primary = os.path.join(input_dir, "primary")
        secondary = os.path.join(input_dir, "secondary")
        try:
            request.files["primary"].save(primary)
            request.files["secondary"].save(secondary)
        except KeyError:
            return make_response(jsonify(error="Missing parameter 'primary' or 'secondary'"), 422)

        timeout = request.form.get('timeout', None)

        cmd = (BINDIFF_DIFFER, "--primary", primary, "--secondary", secondary, "--output_dir", output_dir)
        logger.info("Executing %s", " ".join("'%s'" % x for x in cmd))
        check_call(cmd, cwd = output_dir, timeout = timeout)
        db_path = [os.path.join(output_dir, x) for x in os.listdir(output_dir)]
        if len(db_path) != 1:
            return make_response(jsonify(error = "BinDiff generated 0 or several output files"), 500)
        return send_file(open(db_path[0], "rb"), as_attachment = True, attachment_filename = "BinDiff.sqlite3", mimetype = "application/binary")
    except OSError as err:
        if err.errno == -9:
            return make_response(jsonify(error = "Program execution timed out"), 408)
        else:
            return make_response(jsonify(error = "Program execution failed with error %d" % err.errno), 500)
    finally:
        shutil.rmtree(input_dir)
        shutil.rmtree(output_dir) 
Example 29
Project: BASS   Author: Cisco-Talos   File: ida_service.py    GNU General Public License v2.0 5 votes vote down vote up
def bindiff_export():
    """
    Run the IDA Pro autoanalysis on the input file and export a BinExport database.
    :param input: The input file
    :return: Status code 200 and a JSON object containing the output database
        name in key 'output', or status code 422 on invalid parameters, 408 on
        timeout or 500 on other errors.
    """
    logger.info("bindiff_export called")

    directory = None
    try:
        directory = tempfile.mkdtemp()
        if len(request.files) != 1:
            return make_response(jsonify(error = "Missing file parameter"), 422)

        filename, file_ = request.files.items()[0]
        input_ = os.path.join(directory, sanitize_filename(filename))
        file_.save(input_)

        output = os.path.join(directory, "output.BinExport")

        timeout = request.form.get('timeout', None)
        is_64_bit = request.form.get('is_64_bit', True)
        try:
            run_ida(input_, is_64_bit, timeout, os.path.join(PREFIX, "export_binexport_pickle.py"), "binexport", output)
            logger.info("Command completed successfully")
            return send_file(open(output, "rb"), as_attachment = True, attachment_filename = "%s.BinExport" % filename, mimetype = "application/binary")
        except TimeoutError:
            return jsonify(error = "Program execution timed out"), 408
        except OSError as err:
            return jsonify(error = "Program execution failed with error %d" % err.errno), 500
            
    finally:
        if directory is not None:
            shutil.rmtree(directory) 
Example 30
Project: BASS   Author: Cisco-Talos   File: ida_service.py    GNU General Public License v2.0 5 votes vote down vote up
def bindiff_compare():
    logger.info("bindiff_compare called")

    input_dir = tempfile.mkdtemp()
    output_dir = tempfile.mkdtemp()
    try:
        primary = os.path.join(input_dir, "primary")
        secondary = os.path.join(input_dir, "secondary")
        try:
            request.files["primary"].save(primary)
            request.files["secondary"].save(secondary)
        except KeyError:
            return make_response(jsonify(error="Missing parameter 'primary' or 'secondary'"), 422)

        timeout = request.form.get('timeout', None)

        cmd = (BINDIFF_DIFFER, "--primary", primary, "--secondary", secondary, "--output_dir", output_dir)
        logger.info("Executing %s", " ".join("'%s'" % x for x in cmd))
        check_call(cmd, cwd = output_dir, timeout = timeout)
        db_path = [os.path.join(output_dir, x) for x in os.listdir(output_dir)]
        if len(db_path) != 1:
            return make_response(jsonify(error = "BinDiff generated 0 or several output files"), 500)
        return send_file(open(db_path[0], "rb"), as_attachment = True, attachment_filename = "BinDiff.sqlite3", mimetype = "application/binary")
    except OSError as err:
        if err.errno == -9:
            return make_response(jsonify(error = "Program execution timed out"), 408)
        else:
            return make_response(jsonify(error = "Program execution failed with error %d" % err.errno), 500)
    finally:
        shutil.rmtree(input_dir)
        shutil.rmtree(output_dir) 
Example 31
Project: zmirror   Author: aploium   File: utils.py    MIT License 5 votes vote down vote up
def generate_simple_resp_page(errormsg=b'We Got An Unknown Error', error_code=500):
    """

    :type errormsg: bytes
    :type error_code: int
    :rtype: Response
    """
    return make_response(errormsg, error_code) 
Example 32
Project: flasky   Author: RoseOu   File: flask_httpauth.py    MIT License 5 votes vote down vote up
def error_handler(self, f):
        @wraps(f)
        def decorated(*args, **kwargs):
            res = f(*args, **kwargs)
            if type(res) == str:
                res = make_response(res)
                res.status_code = 401
            if 'WWW-Authenticate' not in res.headers.keys():
                res.headers['WWW-Authenticate'] = self.authenticate_header()
            return res
        self.auth_error_callback = decorated
        return decorated 
Example 33
Project: Bluemix-ServiceBroker   Author: IBM-Cloud   File: bmx-sample-broker.py    Apache License 2.0 5 votes vote down vote up
def bind(instance_id, binding_id):
    # Bind an existing instance with the given org and space
    #
    # PUT /v2/service_instances/<instance_id>/service_bindings/<binding_id>:
    #     <instance_id> is the Cloud Controller provided
    #       value used to provision the instance
    #     <binding_id> is provided by the Cloud Controller
    #       and will be used for future unbind requests
    #
    # BODY:
    #     {
    #       "plan_id":           "<plan-guid>",
    #       "service_id":        "<service-guid>",
    #       "app_guid":          "<app-guid>"
    #     }
    #
    # return:
    #     JSON document with credentails and access details
    #     for the service based on this binding
    #     http://docs.cloudfoundry.org/services/binding-credentials.html

    if request.headers['Content-Type'] != 'application/json':
        abort(415, 'Unsupported Content-Type: expecting application/json')

    # get the JSON document in the BODY
    binding_details = request.get_json()

    # bind would call the service here
    # not done to keep our code simple for the tutorial


    # return result to the Bluemix Cloud Controller
    result={"credentials": {"uri": "testme"}}
    return make_response(jsonify(result),201)

#
# Unbind
# 
Example 34
Project: radius-1xtest   Author: shanghai-edu   File: views.py    Apache License 2.0 5 votes vote down vote up
def code():
    """生成验证码
    """
    from io import BytesIO

    output = BytesIO()
    code_img, code_str = create_validate_code()
    code_img.save(output, 'jpeg')
    img_data=output.getvalue()
    output.close()
    response = make_response(img_data)
    response.headers['Content-Type'] = 'image/jpg'
    session['code_text'] = code_str
    return response 
Example 35
Project: PathDump   Author: PathDump   File: agent.py    Apache License 2.0 5 votes vote down vote up
def not_found (error):
    return make_response (json.dumps ({'error': 'Not found'}), 404) 
Example 36
Project: flask-observability   Author: adimian   File: test_extension.py    MIT License 5 votes vote down vote up
def app_with_login_manager():
    app = Flask("demo")
    app.config["TESTING"] = True
    app.config["SECRET_KEY"] = "thisisverysecret"
    app.config["OBSERVE_AUTO_BIND_VIEWS"] = True
    Observability(app, hostname="somehost")
    login_manager = LoginManager(app)
    login_manager.init_app(app)

    class User(UserMixin):
        username = "alice"

        def get_id(self):
            return 1

    @app.route("/login", methods=["GET"])
    def login_handler():
        if request.form.get("username") == "bad":
            abort(403)
        return make_response("", 200)

    @app.route("/hello", methods=["GET"])
    def hello():
        from flask_login import current_user, login_user

        login_user(User())

        return make_response("hello, {}".format(current_user.username), 200)

    @app.route("/error", methods=["GET"])
    def error():
        errorcode = request.form.get("errorcode")
        if errorcode is not None:
            abort(int(errorcode))
        return make_response("", 200)

    with app.app_context():
        yield app 
Example 37
Project: IBM-Waston-apply   Author: littlewizardLI   File: welcome.py    Apache License 2.0 5 votes vote down vote up
def check():  
    if request.method == 'GET':  
        token = 'changshunowcs'   
        signature = request.args.get('signature', '')  
        echostr = request.args.get('echostr', '')  
        timestamp = request.args.get('timestamp', '')  
        nonce = request.args.get('nonce', '')  
        tmp = [timestamp, nonce, token]  
        tmp.sort()  
        tmp = ''.join(tmp)  
        if ( hashlib.sha1(tmp).hexdigest() == signature ):    
            return make_response(echostr)  
    else:
        recMsg = receive.parse_xml(request.stream.read())
        if isinstance(recMsg, receive.Msg):
            toUser = recMsg.FromUserName
            fromUser = recMsg.ToUserName
            if recMsg.MsgType == 'text':
                textContent1 = recMsg.Content
                textContent2 = translate.Translate(textContent1)
                textContent3 = poem.MakePoem(textContent2)
                replyMsg = reply.TextMsg(toUser, fromUser, textContent3)
                return replyMsg.send()
            if recMsg.MsgType == 'image':
                mediaId = recMsg.MediaId
                mediaUrl = recMsg.PicUrl
                imgContent1 = visual.VisualContent(mediaUrl)
                imgContent2 = translate.Translate(imgContent1) 
                content = poem.MakePoem(imgContent2)
                #content = "url: " + mediaUrl
                replyMsg = reply.TextMsg(toUser, fromUser, content)
                return replyMsg.send()
            else:
                return reply.Msg().send()
        else:
            print ("...")
            return reply.Msg().send() 
Example 38
Project: ras-frontstage   Author: ONSdigital   File: info.py    MIT License 5 votes vote down vote up
def get_info():
    info = {
        "name": 'ras-frontstage',
        "version": app.config['VERSION'],
    }
    info = dict(_health_check, **info)

    return make_response(jsonify(info), 200) 
Example 39
Project: ras-frontstage   Author: ONSdigital   File: surveys_list.py    MIT License 5 votes vote down vote up
def get_survey_list(session, tag):
    """
    Displays the list of surveys for the respondent by tag.  A tag represents the state the
    survey is in (e.g., todo, history, etc)
    """
    logger.info("Retrieving survey todo list")
    party_id = session.get('party_id')
    business_id = request.args.get('business_party_id')
    survey_id = request.args.get('survey_id')
    already_enrolled = request.args.get('already_enrolled')

    survey_list = party_controller.get_survey_list_details_for_party(party_id, tag, business_party_id=business_id,
                                                                     survey_id=survey_id)

    sorted_survey_list = sorted(survey_list, key=lambda k: datetime.strptime(k['submit_by'], '%d %b %Y'), reverse=True)

    if tag == 'todo':
        added_survey = True if business_id and survey_id and not already_enrolled else None
        response = make_response(render_template('surveys/surveys-todo.html',
                                                 sorted_surveys_list=sorted_survey_list,
                                                 added_survey=added_survey, already_enrolled=already_enrolled))

        # Ensure any return to list of surveys (e.g. browser back) round trips the server to display the latest statuses
        response.headers.set("Cache-Control", "no-cache, max-age=0, must-revalidate, no-store")

        return response
    else:
        return render_template('surveys/surveys-history.html', sorted_surveys_list=sorted_survey_list, history=True) 
Example 40
Project: ras-frontstage   Author: ONSdigital   File: logout.py    MIT License 5 votes vote down vote up
def logout():
    # Delete user session in redis
    session_key = request.cookies.get('authorization')
    session = SessionHandler()
    session.delete_session(session_key)
    if request.args.get('csrf_error'):
        flash('To help protect your information we have signed you out.', 'info')
    # Delete session cookie
    response = make_response(redirect(url_for('sign_in_bp.login', next=request.args.get('next'))))
    response.set_cookie('authorization', value='', expires=0)
    return response 
Example 41
Project: RNASEqTool   Author: armell   File: __init__.py    MIT License 5 votes vote down vote up
def output_json(data, code, headers=None):
    resp = make_response(data.to_json(), code)
    resp.headers.extend(headers.items().append({"Location": request.base_url}) or {"Location": request.base_url})

    return resp 
Example 42
Project: RNASEqTool   Author: armell   File: __init__.py    MIT License 5 votes vote down vote up
def output_csv(data, code, headers=None):
    strbuffer = StringIO()
    data.to_csv(strbuffer, index=False)
    resp = make_response(strbuffer.getvalue(), code)
    resp.headers.extend(headers.items().append({"Location": request.base_url}) or {"Location": request.base_url})

    return resp 
Example 43
Project: RNASEqTool   Author: armell   File: __init__.py    MIT License 5 votes vote down vote up
def output_html(data, code, headers=None):
    resp = make_response(data.to_html(), code)
    resp.headers.extend(headers.items().append({"Location": request.base_url}) or {"Location": request.base_url})

    return resp 
Example 44
Project: RNASEqTool   Author: armell   File: __init__.py    MIT License 5 votes vote down vote up
def output_pdf(data, code, headers=None):
    resp = make_response(data.to_pdf(), code)
    resp.headers.extend(headers.items().append({"Location": request.base_url}) or {"Location": request.base_url})

    return resp 
Example 45
Project: activitypump-server   Author: w3c-social   File: views.py    Apache License 2.0 5 votes vote down vote up
def show_db_stuff():
    response = make_response(json.dumps(db.USERS))
    response.headers['Content-Type'] = 'application/json'
    return response 
Example 46
Project: sinking   Author: Arteneko   File: boot.py    Apache License 2.0 5 votes vote down vote up
def res(data, error=None):
    response = make_response(dumps({
        'success': error is None,
        'error': error,
        'data': data
    }))
    response.headers['Content-Type'] = 'application/json'
    return response 
Example 47
Project: openvsd   Author: Numergy   File: vsd_mock.py    Apache License 2.0 5 votes vote down vote up
def bag_object():
    msg = ("<html><head><title>JBoss Web/7.0.17.Final - Error report</title>"
           " </head><body><h1>HTTP Status 400 - </h1><HR size=\"1\" noshade=\"noshade\">"
           "<p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>"
           "description</b> <u>The request sent by the client was syntactically incorrect ()."
           "</u></p><HR size=\"1\" noshade=\"noshade\"><h3>JBoss Web/7.0.17.Final</h3>"
           "</body></html>")
    make_response(msg, '405') 
Example 48
Project: openvsd   Author: Numergy   File: vsd_mock.py    Apache License 2.0 5 votes vote down vote up
def object_show(obj_name, obj_id):
    data_src = get_object_id(obj_name, 'ID', obj_id)
    if data_src == {}:
        return make_response(json.dumps(
            get_object_id('messages', 'name', 'not found')['message']), '404')
    return json.dumps([get_object_id(obj_name, 'ID', obj_id)]) 
Example 49
Project: openvsd   Author: Numergy   File: vsd_mock.py    Apache License 2.0 5 votes vote down vote up
def get_object_list_with_parent(parent_name, parent_id, obj_name):
    # Check parent exist but don't check parent own objects
    data_src = get_object_id(parent_name, 'ID', parent_id)
    if data_src == {}:
        return make_response(json.dumps(
            get_object_id('messages', 'name', 'not found')['message']), '404')
    filter = request.headers.get('X-Nuage-Filter')
    return json.dumps(filter_objets(obj_name, filter)) 
Example 50
Project: openvsd   Author: Numergy   File: vsd_mock.py    Apache License 2.0 5 votes vote down vote up
def gateway_create():
    data_update = json.loads(request.data)
    if 'gateways' not in database:
        database.update({'gateways': []})
    data_src = get_object_id('gateways', 'systemID', data_update['systemID'])
    if data_src != {}:
        return make_response(json.dumps(
            get_object_id('messages', 'name', 'already exists')['message']), '409')

    id = '0'
    for object in database['gateways']:
        if (object['ID'][0] > id):
            id = object['ID'][0]

    id = increment_id(id)
    new = {'ID': id,
           'systemID': '9.9.9.9',
           'name': 'gateway-unknown',
           'description': 'None',
           'pending': 'False',
           'redundancyGroupID': 'None',
           'personality': 'VRSG'}
    new.update(data_update)
    database['gateways'].append(new)

    return json.dumps([get_object_id('gateways', 'ID', id)]) 
Example 51
Project: openvsd   Author: Numergy   File: vsd_mock.py    Apache License 2.0 5 votes vote down vote up
def gatewayredundantgroup_create_with_enterprise_id(enterprise_id):
    data_update = json.loads(request.data)
    if 'redundancygroups' not in database:
        database.update({'redundancygroups': []})

    id = get_object_id('redundancygroups', 'gatewayPeer1ID',
                       data_update['gatewayPeer1ID'])
    if id != {}:
        return make_response(json.dumps(
            get_object_id('messages', 'name', 'already in use')['message']), '409')

    id = get_object_id('redundancygroups', 'gatewayPeer2ID',
                       data_update['gatewayPeer2ID'])
    if id != {}:
        return make_response(json.dumps(
            get_object_id('messages', 'name', 'already in use')['message']), '409')

    id = '0'
    for object in database['gateways']:
        if (object['ID'][0] > id):
            id = object['ID'][0]

    id = increment_id(id)
    new = {'ID': id,
           'name': 'gw-group-unknown',
           'description': 'None',
           'entityScope': 'ENTERPRISE',
           'enterpriseID': enterprise_id,
           'gatewayPeer1ID': '11111111-1111-1111-111111111111',
           'gatewayPeer2ID': '22222222-2222-2222-222222222222',
           'gatewayPeer1Name': 'gateway-1',
           'gatewayPeer2Name': 'gateway-2',
           'redundantGatewayStatus': 'SUCCESS',
           'personality': 'VRSG'}

    new.update(data_update)
    database['redundancygroups'].append(new)
    return json.dumps([get_object_id('redundancygroups', 'ID', id)]) 
Example 52
Project: openvsd   Author: Numergy   File: vsd_mock.py    Apache License 2.0 5 votes vote down vote up
def object_create(obj_name):
    data_update = json.loads(request.data)
    data_src = get_object_id(obj_name, 'name', data_update['name'])
    if data_src != {}:
        return make_response(json.dumps(
            get_object_id('messages', 'name', 'already exists')['message']), '409')
    new = {'name': data_update['name'],
           'ID': '255d9673-7281-43c4-be57-fdec677f6e07',
           'description': 'None'}
    database[obj_name].append(new)
    return json.dumps([get_object_id(obj_name, 'ID', '255d9673-7281-43c4-be57-fdec677f6e07')]) 
Example 53
Project: openvsd   Author: Numergy   File: vsd_mock.py    Apache License 2.0 5 votes vote down vote up
def object_delete(obj_name, obj_id):
    data_src = get_object_id(obj_name, 'ID', obj_id)
    if data_src == {}:
        return make_response(json.dumps(
            get_object_id('messages', 'name', 'not found')['message']), '404')
    database[obj_name].remove(data_src)
    return '{}' 
Example 54
Project: lc3ctf   Author: emc2314   File: server.py    MIT License 5 votes vote down vote up
def error(msg):
    """Displays an error message"""

    if msg in lang['error']:
        error = lang['error'][msg]
    else:
        error = lang['error']['unknown']

    login, user = get_user()

    render = render_template('frame.html', lang=lang, page='error.html',
                             message=error['msg'], login=login, user=user, active=default_active)
    return make_response(render), error['ec'] 
Example 55
Project: lc3ctf   Author: emc2314   File: server.py    MIT License 5 votes vote down vote up
def achivements():
    """Displays the achivements menu"""

    login, user = get_user()
    active = default_active.copy()
    active['achivements'] = 'active'

    db = dataset.connect(dbfile)
    achis = db.query('''select a.achi_id from achivements a
                where a.user_id = :user_id''', user_id=session['user_id'])
    achi = [a['achi_id'] for a in list(achis)]
    db.executable.close()

    ACh = [a for a in lc3_achivements if a['id'] in achi and not a['hidden']]
    ach = [a for a in lc3_achivements if a['id'] not in achi and not a['hidden']]
    ACH = [a for a in lc3_achivements if a['id'] in achi and a['hidden']]
    l___ = len(lc3_achivements)
    lAC_ = len([a for a in lc3_achivements if a['id'] in achi])
    lACh = len(ACh)
    lach = len(ach)
    lACH = len(ACH)
    l__H = len([a for a in lc3_achivements if a['hidden']])

    # Render template
    render = render_template('frame.html', lang=lang, page='achivements.html',
                             login=login, user=user, active=active,
                             ACh=ACh, ach=ach, ACH=ACH,
                             lACh=lACh, lach=lach, lACH=lACH, l__H=l__H,
                             width='%.2f'%(100*lAC_/l___))
    return make_response(render) 
Example 56
Project: lc3ctf   Author: emc2314   File: server.py    MIT License 5 votes vote down vote up
def index():
    """Displays the main page"""

    login, user = get_user()

    # Render template
    render = render_template('frame.html', lang=lang,
                             page='main.html', login=login, user=user, active=default_active)
    return make_response(render)


# Load config 
Example 57
Project: invenio-deposit   Author: inveniosoftware   File: serializers.py    MIT License 5 votes vote down vote up
def json_file_serializer(obj, status=None):
    """JSON File Serializer.

    :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance.
    :param status: A HTTP Status. (Default: ``None``)
    :returns: A Flask response with JSON data.
    :rtype: :py:class:`flask.Response`.
    """
    return make_response(jsonify(file_serializer(obj)), status) 
Example 58
Project: invenio-deposit   Author: inveniosoftware   File: serializers.py    MIT License 5 votes vote down vote up
def json_files_serializer(objs, status=None):
    """JSON Files Serializer.

    :parma objs: A list of:class:`invenio_files_rest.models.ObjectVersion`
        instances.
    :param status: A HTTP Status. (Default: ``None``)
    :returns: A Flask response with JSON data.
    :rtype: :py:class:`flask.Response`.
    """
    files = [file_serializer(obj) for obj in objs]
    return make_response(json.dumps(files), status) 
Example 59
Project: hackernewsbot   Author: phil-r   File: main.py    MIT License 5 votes vote down vote up
def story_redirect(short_id):
  """Redirect to story url"""
  try:
    story_id = str(shortener.decode(short_id))
  except:
    return abort(400)
  redirect_url = memcache.get(story_id)
  if not redirect_url:
    story = ndb.Key(StoryPost, story_id).get()
    if not story:
      return make_response('<h1>Service Unavailable</h1><p>Try again later</p>', 503, {'Retry-After': 5})
    story.add_memcache()
    redirect_url = story.url
  return redirect(redirect_url) 
Example 60
Project: aiolocust   Author: kpidata   File: web.py    MIT License 5 votes vote down vote up
def swarm(request):
    assert request.method == "POST"

    locust_count = int(request.form["locust_count"])
    hatch_rate = float(request.form["hatch_rate"])
    runners.locust_runner.start_hatching(locust_count, hatch_rate)
    response = make_response(json.dumps({'success':True, 'message': 'Swarming started'}))
    response.headers["Content-type"] = "application/json"
    return response 
Example 61
Project: aiolocust   Author: kpidata   File: web.py    MIT License 5 votes vote down vote up
def stop(request):
    runners.locust_runner.stop()
    response = make_response(json.dumps({'success':True, 'message': 'Test stopped'}))
    response.headers["Content-type"] = "application/json"
    return response 
Example 62
Project: aiolocust   Author: kpidata   File: web.py    MIT License 5 votes vote down vote up
def request_stats_csv(request):
    rows = [
        ",".join([
            '"Method"',
            '"Name"',
            '"# requests"',
            '"# failures"',
            '"Median response time"',
            '"Average response time"',
            '"Min response time"', 
            '"Max response time"',
            '"Average Content Size"',
            '"Requests/s"',
        ])
    ]
    
    for s in chain(_sort_stats(runners.locust_runner.request_stats), [runners.locust_runner.stats.aggregated_stats("Total", full_request_history=True)]):
        rows.append('"%s","%s",%i,%i,%i,%i,%i,%i,%i,%.2f' % (
            s.method,
            s.name,
            s.num_requests,
            s.num_failures,
            s.median_response_time,
            s.avg_response_time,
            s.min_response_time or 0,
            s.max_response_time,
            s.avg_content_length,
            s.total_rps,
        ))

    response = make_response("\n".join(rows))
    file_name = "requests_{0}.csv".format(time())
    disposition = "attachment;filename={0}".format(file_name)
    response.headers["Content-type"] = "text/csv"
    response.headers["Content-disposition"] = disposition
    return response 
Example 63
Project: aiolocust   Author: kpidata   File: web.py    MIT License 5 votes vote down vote up
def distribution_stats_csv(request):
    rows = [",".join((
        '"Name"',
        '"# requests"',
        '"50%"',
        '"66%"',
        '"75%"',
        '"80%"',
        '"90%"',
        '"95%"',
        '"98%"',
        '"99%"',
        '"100%"',
    ))]
    for s in chain(_sort_stats(runners.locust_runner.request_stats), [runners.locust_runner.stats.aggregated_stats("Total", full_request_history=True)]):
        if s.num_requests:
            rows.append(s.percentile(tpl='"%s",%i,%i,%i,%i,%i,%i,%i,%i,%i,%i'))
        else:
            rows.append('"%s",0,"N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"' % s.name)

    response = make_response("\n".join(rows))
    file_name = "distribution_{0}.csv".format(time())
    disposition = "attachment;filename={0}".format(file_name)
    response.headers["Content-type"] = "text/csv"
    response.headers["Content-disposition"] = disposition
    return response 
Example 64
Project: aiolocust   Author: kpidata   File: web.py    MIT License 5 votes vote down vote up
def exceptions_csv(request):
    data = StringIO()
    writer = csv.writer(data)
    writer.writerow(["Count", "Message", "Traceback", "Nodes"])
    for exc in runners.locust_runner.exceptions.values():
        nodes = ", ".join(exc["nodes"])
        writer.writerow([exc["count"], exc["msg"], exc["traceback"], nodes])
    
    data.seek(0)
    response = make_response(data.read())
    file_name = "exceptions_{0}.csv".format(time())
    disposition = "attachment;filename={0}".format(file_name)
    response.headers["Content-type"] = "text/csv"
    response.headers["Content-disposition"] = disposition
    return response 
Example 65
Project: injuben   Author: injuben   File: in_juben.py    MIT License 5 votes vote down vote up
def examples(path):
    f = open("examples/" + path, "r")
    r = make_response(f.read())
    f.close()
    r.headers['Content-Type'] = 'text/plain; charset=UTF-8'
    return r 
Example 66
Project: injuben   Author: injuben   File: in_juben.py    MIT License 5 votes vote down vote up
def preview():
    input = StringIO(request.form.get('in-juben-text'))
    has_scene_num = bool(request.form.get('in-has-scene-num'))
    first_page_number = bool(request.form.get('in-first-page-num'))
    strong_scene_heading = bool(request.form.get('in-strong-scene-heading'))
    in_lang = request.form.get('in-lang')
    tmp_file = tempfile.SpooledTemporaryFile()
    suffix = "pdf"
    try:
        if in_lang == 'zh':
            input = normalize.parse(input)
        filename = input.readline().replace("Title:", '').strip()
        input.seek(0)
        screenplay = fountain.parse(input)
        if in_lang == 'zh':
            to_pdf(screenplay, tmp_file._file, is_strong=strong_scene_heading, has_scene_num=has_scene_num, first_page_number=first_page_number)
        else:
            to_en_pdf(screenplay, tmp_file._file, is_strong=strong_scene_heading)
        tmp_file.seek(0)
        encoded_string = base64.b64encode(tmp_file.read()).decode('ascii')
        r = make_response('{"filename":"' + filename + '", "suffix":"' + suffix + '", "content":"' + encoded_string + '"}')
        r.headers['Content-Type'] = 'text/plain; charset=UTF-8'
        return r
    except:
        return locales().get('_')('Invalid Format'), 500
    finally:
        if tmp_file:
           tmp_file.close() 
Example 67
Project: Python-RESTful-API   Author: HawkEleven   File: pymysl03.py    Apache License 2.0 5 votes vote down vote up
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 403) 
Example 68
Project: Python-RESTful-API   Author: HawkEleven   File: pymysl03.py    Apache License 2.0 5 votes vote down vote up
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404) 
Example 69
Project: hassutnimet_net   Author: aajanki   File: namegenserver.py    MIT License 5 votes vote down vote up
def no_cache(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        resp = make_response(fn(*args, **kwargs))
        resp.cache_control.no_cache = True
        return resp
    return wrapped 
Example 70
Project: liteshort   Author: 132ikl   File: liteshort.py    MIT License 5 votes vote down vote up
def main_redir(url):
    long = get_long(url)
    if long:
        resp = make_response(redirect(long, 301))
    else:
        flash('Short URL "' + url + '" doesn\'t exist', 'error')
        resp = make_response(redirect(url_for('main')))
    resp.headers.set('Cache-Control', 'no-store, must-revalidate')
    return resp 
Example 71
Project: beavy   Author: beavyHQ   File: __init__.py    Mozilla Public License 2.0 5 votes vote down vote up
def fallbackRender(template, key=None):

    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            resp = fn(*args, **kwargs)
            if isinstance(resp, ResponseBase):
                return resp

            data, code, headers = unpack(resp)

            accepted = set(request.accept_mimetypes.values())
            explicit = not (not request.args.get("json", False))
            if len(accepted & API_MIMETYPES) or explicit:
                # we've found one, return json
                if isinstance(data, MarshalResult):
                    data = data.data
                resp = make_response(json.dumps(data,
                                                indent=explicit and 4 or 0),
                                     code)
                ct = 'application/json'
            else:
                resp = make_response(render_template(template,
                                                     key=key,
                                                     data=data),
                                     code)
                ct = "text/html"

            if headers:
                resp.headers.update(headers)
            resp.headers["Content-Type"] = ct
            return resp

        return decorated_view
    return wrapper 
Example 72
Project: Flask_Blog   Author: sugarguo   File: views.py    GNU General Public License v3.0 5 votes vote down vote up
def ckupload():
    #site_info = site_get()
    """CKEditor file upload"""
    error = ''
    url = ''
    callback = request.args.get("CKEditorFuncNum")

    if request.method == 'POST' and 'upload' in request.files:
        fileobj = request.files['upload']
        fname, fext = os.path.splitext(fileobj.filename)
        rnd_name = '%s%s' % (gen_rnd_filename(), fext)

        filepath = os.path.join(app.static_folder, 'upload', rnd_name)

        # 检查路径是否存在,不存在则创建
        dirname = os.path.dirname(filepath)
        if not os.path.exists(dirname):
            try:
                os.makedirs(dirname)
            except:
                error = 'ERROR_CREATE_DIR'
        elif not os.access(dirname, os.W_OK):
            error = 'ERROR_DIR_NOT_WRITEABLE'

        if not error:
            fileobj.save(filepath)
            url = url_for('static', filename='%s/%s' % ('upload', rnd_name))
    else:
        error = 'post error'
    #print callback
    res = """<script type="text/javascript">
  window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');
</script>""" % (callback, url, error)

    response = make_response(res)
    response.headers["Content-Type"] = "text/html"
    return response 
Example 73
Project: badge-o-matic   Author: markuslindenberg   File: webapp.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def badge():
    name = request.form['name'][:MAX_CHARS_PER_LINE] if 'name' in request.form else ''
    name2 = request.form['name2'][:MAX_CHARS_PER_LINE] if 'name2' in request.form else ''
    nick = request.form['nick'][:MAX_CHARS_PER_LINE] if 'nick' in request.form else ''
    community = request.form['community'][:MAX_CHARS_PER_LINE] if 'community' in request.form else ''

    pdf = BytesIO()
    c = Canvas(pdf, pagesize=(BADGE_W, BADGE_H))

    c.translate(ORIGIN_X, ORIGIN_Y)

    ico_center = 7*mm
    offset = HEIGHT+2*mm

    c.setFillGray(0.66)
    c.setFont('Awesome', 42)
    c.drawCentredString(ico_center, offset-42*pica/12, '\uf007')
    c.setFont('Awesome', 38)
    c.drawCentredString(ico_center, offset-(2*42+40)*pica/12, '\uf1fa')
    c.drawCentredString(ico_center, offset-(2*42+2*40)*pica/12, '\uf041')

    txt_start = 15*mm

    c.setFillGray(0.0)
    c.setFont('LeagueGothic', 42)
    c.drawString(txt_start, offset-42*pica/12, name)
    c.drawString(txt_start, offset-2*42*pica/12, name2)
    c.setFont('LeagueGothic', 38)
    c.drawString(txt_start, offset-(2*42+40)*pica/12, nick)
    c.drawString(txt_start, offset-(2*42+2*40)*pica/12, community)

    evt_width = 38*pica/12
    evt_start = WIDTH - evt_width

    img_width = 20*mm
    img_start = evt_start - img_width
    c.drawImage(path.join(path.dirname(__file__), 'images/ffrhein_logo_claim_line_rot.png'), img_start, 0, img_width, HEIGHT, mask=None, preserveAspectRatio=True, anchor='c')

    c.rotate(90)
    c.rect(0, -WIDTH, HEIGHT, evt_width, 0, 1)
    c.setFillGray(1.0)
    c.drawCentredString(HEIGHT/2, -WIDTH+MARGIN_R, 'routing days')  

    c.showPage()
    c.save()
    _print(pdf.getvalue())
    pdf.close()

    # response = make_response('Meh')
    # response.headers['Content-Type'] = 'text/plain'
    # return response
    return redirect('/badge/printing.html') 
Example 74
Project: BASS   Author: Cisco-Talos   File: server.py    GNU General Public License v2.0 4 votes vote down vote up
def function_add():
    global Session

    session = Session()
    filename, file_ = request.files.items()[0]
    db = Database(pickle.load(file_))
    arch_name = db.architecture_name
    if arch_name == "metapc":
        arch_name = "x86"
    # Get the architecture, if it already exists
    try:
        arch = session.query(Architecture).filter(Architecture.name == arch_name and \
                Architecture.bits == db.architecture_bits and \
                Architecture.little_endian == db.architecture_endianness == "little").one()
    except NoResultFound:
        arch = Architecture(name = arch_name, 
                            bits = db.architecture_bits, 
                            little_endian = db.architecture_endianness == "little")
        session.add(arch)

    for func in db.functions:
        raw_hash = _function_calculate_raw_sha256(func)
        size = _function_get_size(func)

        try:
            function = session.query(Function).filter(Function.raw_sha256 == raw_hash and \
                    Function.size == size and \
                    Function.arch == arch.id).one()
        except NoResultFound:
            mnem_hash = _function_calculate_mnem_sha256(func)
            instrs = _function_count_instructions(func)
            bbs = _function_count_basic_blocks(func)
            loops = _function_count_loops(func)
            trans = _function_count_transitions(func)
            func_json = _function_get_json(func)

            function = Function(
                    raw_sha256 = raw_hash,
                    size = size,
                    mnem_sha256 = mnem_hash,
                    executable = db.sha256,
                    entry_point = func.entry_point,
                    data = json.dumps(func_json),
                    architecture = arch.id,
                    basic_blocks = bbs,
                    transitions = trans,
                    loops = loops)
            session.add(function)

    session.commit()

    return make_response("", 200) 
Example 75
Project: BASS   Author: Cisco-Talos   File: ida_service.py    GNU General Public License v2.0 4 votes vote down vote up
def idb_export():
    """
    Run the IDA Pro autoanalysis on the input file and export the IDB database.
    :param input: The input file
    :return: Status code 200 and a JSON object containing the output database
        name in key 'output', or status code 422 on invalid parameters, 408 on
        timeout or 500 on other errors.
    """
    logger.info("idb_export called")

    directory = None
    try:
        directory = tempfile.mkdtemp()

        if len(request.files) != 1:
            return make_response(jsonify(error = "Missing file parameter"), 422)

        filename, file_ = request.files.items()[0]
        input_ = os.path.join(directory, sanitize_filename(filename))
        file_.save(input_)

        # i386
        outname = "%s%s" % (input_, ".idb")

        timeout = request.form.get('timeout', None)
        is_64_bit = request.form.get('is_64_bit', True)

        # x86-64
        if is_64_bit:
            outname = "%s%s" % (input_, ".i64")

        output = os.path.join(directory, outname)
        
        try:
            run_ida(input_, is_64_bit, timeout, os.path.join(PREFIX, "export_binexport_pickle.py"), "binexport", output)
            logger.info("Command completed successfully")
            return send_file(open(output, "rb"), as_attachment = True, attachment_filename = "%s.ida_db" % filename, mimetype = "application/binary")
        except TimeoutError:
            return jsonify(error = "Program execution timed out"), 408
        except OSError as err:
            return jsonify(error = "Program execution failed with error %d" % err.errno), 500
    finally:
        pass
        #if directory is not None:
        #    shutil.rmtree(directory) 
Example 76
Project: BASS   Author: Cisco-Talos   File: ida_service.py    GNU General Public License v2.0 4 votes vote down vote up
def bindiff_pickle_export():
    """
    Run the IDA Pro autoanalysis on the input file and export a BinExport database.
    :param input: The input file
    :return: Status code 200 and a JSON object containing the output database
        name in key 'output', or status code 422 on invalid parameters, 408 on
        timeout or 500 on other errors.
    """
    logger.info("bindiff_pickle_export called")

    directory = None
    try:
        directory = tempfile.mkdtemp()
        if len(request.files) != 1:
            return make_response(jsonify(error = "Missing file parameter"), 422)

        filename, file_ = request.files.items()[0]
        input_ = os.path.join(directory, sanitize_filename(filename))
        file_.save(input_)

        output_binexport = os.path.join(directory, "output.BinExport")
        output_pickle = os.path.join(directory, "output.pickle")

        timeout = request.form.get('timeout', None)
        is_64_bit = request.form.get('is_64_bit', True)
        try:
            run_ida(input_, is_64_bit, timeout, os.path.join(PREFIX, "export_binexport_pickle.py"), "binexport_pickle", output_binexport, output_pickle)
            logger.info("Command completed successfully")
            output_tar = os.path.join(directory, "output.tar.gz")
            subprocess.check_call(["tar", "czf", output_tar, os.path.relpath(output_binexport, directory), os.path.relpath(output_pickle, directory)], cwd = directory)
            return send_file(open(output_tar, "rb"), as_attachment = True, attachment_filename = "%s.tar.gz" % filename, mimetype = "application/gzip")
        except TimeoutError:
            return jsonify(error = "Program execution timed out"), 408
        except OSError as err:
            return jsonify(error = "Program execution failed with error %d" % err.errno), 500
    finally:
        if directory is not None:
            shutil.rmtree(directory) 
Example 77
Project: SayluaLegacy   Author: saylua   File: register.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def register():
    if app.config.get('REGISTRATION_DISABLED'):
        flash('Sorry, registration is currently disabled. Check back later!', 'error')
        return redirect('/login')
    form = RegisterForm(request.form)
    form.invite_code.data = get_from_request(request, 'invite_code')

    if not app.config.get('INVITE_ONLY'):
        del form.invite_code

    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        email = form.email.data

        password_hash = User.hash_password(password)
        new_user = User(
            username=username,
            password_hash=password_hash,
            email=email
        )

        db.session.add(new_user)
        db.session.commit()

        if app.config.get('INVITE_ONLY'):
            # Claim the user's invite code if one was used.
            invite_code = register_check.invite_code

            # Note that an invite code should exist assuming the form validation
            # passed... If an empty code gets here, we have a problem.
            invite_code.recipient_id = new_user.id
            db.session.add(invite_code)

        # Add a session to the datastore
        expires = datetime.datetime.utcnow()
        expires += datetime.timedelta(days=app.config['COOKIE_DURATION'])
        new_session = LoginSession(user_id=new_user.id, expires=expires)

        db.session.add(new_session)
        db.session.commit()

        # Generate a matching cookie and redirct
        resp = make_response(redirect('/'))
        resp.set_cookie('session_id', new_session.id, expires=expires)
        resp.set_cookie('user_id', str(new_user.id), expires=expires)

        # Send the confirmation email for the new account.
        send_confirmation_email(new_user)
        return resp

    return render_template('register/register.html', form=form)


# The endpoint to confirm email addresses. 
Example 78
Project: jenca-authentication   Author: bimlauncher   File: storage.py    MIT License 4 votes vote down vote up
def users_route():
    """
    **POST**:

    Create a new user.

    :param email: The email address of the new user.
    :type email: string
    :param password_hash: A password hash to associate with the given ``email``
        address.
    :type password_hash: string
    :reqheader Content-Type: application/json
    :resheader Content-Type: application/json
    :resjson string email: The email address of the new user.
    :resjson string password_hash: The password hash of the new user.
    :status 200: A user with the given ``email`` and ``password_hash`` has been
        created.
    :status 409: There already exists a user with the given ``email``.

    **GET**:

    Get information about all users.

    :reqheader Content-Type: application/json
    :resheader Content-Type: application/json
    :resjsonarr string email: The email address of a user.
    :resjsonarr string password_hash: The password hash of a user.
    :status 200: Information about all users is returned.
    """

    if request.method == 'POST':
        return create_user()

    # It the method type is not POST it is GET.
    details = [
        {'email': user.email, 'password_hash': user.password_hash} for user
        in User.query.all()]

    return make_response(
        json.dumps(details),
        codes.OK,
        {'Content-Type': 'application/json'}) 
Example 79
Project: PIL-RCE-Ghostscript-CVE-2018-16509   Author: farisv   File: app.py    MIT License 4 votes vote down vote up
def upload_file():
    if request.method == 'POST':
        file = request.files.get('image', None)

        if not file:
            flash('No image found')
            return redirect(request.url)

        filename = file.filename
        ext = path.splitext(filename)[1]

        if (ext not in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']):
            flash('Invalid extension')
            return redirect(request.url)

        tmp = tempfile.mktemp("test")
        img_path = "{}.{}".format(tmp, ext)

        file.save(img_path)

        img = Image.open(img_path)
        w, h = img.size
        ratio = 256.0 / max(w, h)

        resized_img = img.resize((int(w * ratio), int(h * ratio)))
        resized_img.save(img_path)

        r = make_response()
        r.data = open(img_path, "rb").read()
        r.headers['Content-Disposition'] = 'attachment; filename=resized_{}'.format(filename)

        unlink(img_path)

        return r

    return render_template_string('''
    <!doctype html>
    <title>Image Resizer</title>
    <h1>Upload an Image to Resize</h1>
    {% with messages = get_flashed_messages() %}
    {% if messages %}
        <ul class=flashes>
        {% for message in messages %}
        <li>{{ message }}</li>
        {% endfor %}
        </ul>
    {% endif %}
    {% endwith %}
    <form method=post enctype=multipart/form-data>
      <p><input type=file name=image>
         <input type=submit value=Upload>
    </form>
    ''') 
Example 80
Project: lc3ctf   Author: emc2314   File: server.py    MIT License 4 votes vote down vote up
def tasks():
    """Displays all the tasks in a grid"""

    login, user = get_user()
    flags = get_flags()
    active = default_active.copy()
    active['tasks'] = 'active'

    db = dataset.connect(dbfile)
    categories = list(db['categories'])

    tasks = db.query('''select c.id as cat_id, t.id as id, c.short_name as cat,
        t.score, t.row, t.name from categories c, tasks t, cat_task c_t
        where c.id = c_t.cat_id and t.id = c_t.task_id''')
    tasks = list(tasks)

    grid = []
    # Find the max row number
    max_row = max(t['row'] for t in tasks)

    for row in range(max_row + 1):

        row_tasks = []
        for cat in categories:

            # Find the task with the correct row
            for task in tasks:
                if task['row'] == row and task['cat_id'] == cat['id']:
                    break
            else:
                task = None

            row_tasks.append(task)

        grid.append(row_tasks)

    db.executable.close()
    # Render template
    render = render_template('frame.html', lang=lang, page='tasks.html',
                             login=login, user=user, categories=categories, grid=grid,
                             flags=flags, active=active)
    return make_response(render)