Python flask.jsonify() Examples

The following are 30 code examples of flask.jsonify(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source File: upload.py    From video2commons with GNU General Public License v3.0 16 votes vote down vote up
def upload():
    f = request.files['file']
    assert f, "Where's my file?"

    filekey = request.form.get('filekey') or str(uuid.uuid1())
    assert RE_ALLOWED_FILEKEYS.match('filekey'), 'Unacceptable file key'

    permpath = getpath(filekey)

    content_range = (f.headers.get('Content-Range') or
                     request.headers.get('Content-Range'))

    if content_range:
        result, kwargs = handle_chunked(f, permpath, content_range)
    else:
        result, kwargs = handle_full(f, permpath)

    kwargs['filekey'] = filekey

    return jsonify(result=result, **kwargs)


# Flask endpoint 
Example #2
Source File: server.py    From BASS with GNU General Public License v2.0 8 votes vote down vote up
def whitelist_add():
    log.info("whitelist_add called")
    try:
        file_ = request.files["file"]
        handle, filename = tempfile.mkstemp()
        os.close(handle)
        file_.save(filename)
        data = request.get_json()
        if data and "functions" in data:
            functions = data["functions"]
        else:
            functions = None
        bass.whitelist_add(filename, functions)
        os.unlink(filename)
    except KeyError:
        log.exception("")
        return make_response(jsonify(message = "Sample file 'file' missing in POST request"), 400)

    return jsonify(message = "OK") 
Example #3
Source File: server.py    From grlc with MIT License 8 votes vote down vote up
def query(user, repo, query_name, subdir=None, spec_url=None, sha=None, content=None):
    """Execute SPARQL query for a specific grlc-generated API endpoint"""
    glogger.info("-----> Executing call name at /{}/{}/{}/{} on commit {}".format(user, repo, subdir, query_name, sha))
    glogger.debug("Request accept header: " + request.headers["Accept"])

    requestArgs = request.args
    acceptHeader = request.headers['Accept']
    requestUrl = request.url
    formData = request.form

    query_response, status, headers = utils.dispatch_query(user, repo, query_name, subdir, spec_url,
                                                           sha=sha, content=content, requestArgs=requestArgs,
                                                           acceptHeader=acceptHeader,
                                                           requestUrl=requestUrl, formData=formData)
    if isinstance(query_response, list):
        query_response = jsonify(query_response)

    return make_response(query_response, status, headers)

### Server routes ### 
Example #4
Source File: server.py    From BASS with GNU General Public License v2.0 7 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 #5
Source File: reconng.py    From bounty_tools with MIT License 7 votes vote down vote up
def run():

    # Setup the jsonrpclib for the recon-ng RPC server, stop the API if it cannot connect to the RPC server.
    try:
        client = jsonrpclib.Server('http://localhost:4141')
        sid = client.init()

        # Get the configuration from JSON POST
        content = request.get_json()
        target_module = content['module']
        target_domain = content['domain']
        print(target_domain, target_module)

        # Set the target domain
        client.add('domains', target_domain, sid)
        print(client.show('domains', sid))
        client.use(target_module, sid)

        # Execute the requested module and return the results
        results = client.run(sid)

        return jsonify(results)

    except:
        return traceback.format_exc(), 500 
Example #6
Source File: sparql.py    From grlc with MIT License 6 votes vote down vote up
def getResponseText(endpoint, query, requestedMimeType):
    """Returns the result and mimetype of executing the given query against 
    the given endpoint.

    Keyword arguments:
    endpoint - URL of sparql endpoint
    query    - SPARQL query to be executed
    requestedMimeType  Type of content requested. can be:
                'text/csv; q=1.0, */*; q=0.1'
                'application/json'
                etc.
    """
    retFormat = _mimeTypeToSparqlFormat(requestedMimeType)

    client = SPARQLWrapper(endpoint)
    client.setQuery(query)
    client.setReturnFormat(retFormat)
    client.setCredentials(static.DEFAULT_ENDPOINT_USER, static.DEFAULT_ENDPOINT_PASSWORD)
    result = client.queryAndConvert()

    if retFormat==JSON:
        result = jsonify(result)

    return result, MIME_FORMAT[retFormat] 
Example #7
Source File: server.py    From Tkinter-GUI-Programming-by-Example with MIT License 5 votes vote down vote up
def user_exists():
    username = request.form.get("username")
    exists = database.user_exists(username)

    return jsonify({
        "exists": exists
    }) 
Example #8
Source File: server.py    From jiji-with-tensorflow-example with MIT License 5 votes vote down vote up
def estimate():
    # 値の正規化のため、リクエストボディで渡された指標データと訓練で使用したデータを統合。
    data = pd.DataFrame({k: [v] for k, v in request.json.items()}).append(trade_data)
    # 正規化したデータを渡して、損益を予測
    results = estimator.estimate(TradeResults(data).all_data().iloc[[0]])
    return jsonify(result=("up" if results[0] == 0 else "down")) 
Example #9
Source File: server.py    From Tkinter-GUI-Programming-by-Example with MIT License 5 votes vote down vote up
def send_message(username):
    data = request.form
    author = data["author"]
    message = data["message"]
    date_sent = arrow.now().timestamp

    conversation_db_path = get_conversation_db_path_for_users({"user_one": author, "user_two": username})
    conversation = Conversation(conversation_db_path)
    conversation.add_message(author, message, date_sent)

    return jsonify({
        "success": True
    }) 
Example #10
Source File: server.py    From Tkinter-GUI-Programming-by-Example with MIT License 5 votes vote down vote up
def index():
    data = {
        "cats": 5,
        "people": 8,
        "dogs": 4
    }

    return jsonify(data) 
Example #11
Source File: server.py    From Tkinter-GUI-Programming-by-Example with MIT License 5 votes vote down vote up
def get_all_users():
    all_users = database.get_all_users()

    return jsonify(all_users) 
Example #12
Source File: terraformize_endpoint.py    From terraformize with GNU Lesser General Public License v3.0 5 votes vote down vote up
def destroy_terraform(module_path: str, workspace_name: str) -> Tuple[str, int]:
    """
    A REST endpoint to destroy terraform modules at a given module path inside the main module directory path at a given
    workspace

    Arguments:
        :param module_path:  the name of the subdirectory for the module inside the "terraform_modules_path" to run
        "terraform destroy" at
        :param workspace_name: the name of the workspace to run "terraform destroy" at

    Returns:
        :return return_body: a JSON of the stdout & stderr from the terraform run
        :return terraform_return_code: the terraform return code

    Exceptions:
        :except FileNotFoundError: will return HTTP 404 with a JSON of the stderr it catch from "terraform init" or
        "terraform destroy"
    """
    try:
        terraform_object = Terraformize(workspace_name, configuration["terraform_modules_path"] + "/" + module_path,
                                        terraform_bin_path=configuration["terraform_binary_path"])
        terraform_return_code, terraform_stdout, terraform_stderr = terraform_object.destroy(
            request.json, configuration["parallelism"]
        )
        return_body = jsonify({
            "init_stdout": terraform_object.init_stdout,
            "init_stderr": terraform_object.init_stderr,
            "stdout": terraform_stdout,
            "stderr": terraform_stderr
        })
        return return_body, terraform_return_code_to_http_code(int(terraform_return_code))
    except FileNotFoundError as error_log:
        return jsonify({"error": str(error_log)}), 404 
Example #13
Source File: server.py    From Tkinter-GUI-Programming-by-Example with MIT License 5 votes vote down vote up
def get_message_history():
    conversation_db_path = get_conversation_db_path_for_users(request.form)
    conversation = Conversation(conversation_db_path)

    history = conversation.get_history()

    return jsonify({
        "history": history
    }) 
Example #14
Source File: server.py    From Tkinter-GUI-Programming-by-Example with MIT License 5 votes vote down vote up
def get_avatar(username):

    avatar_b64 = database.get_user_avatar(username)['avatar']

    return jsonify({
        "avatar": avatar_b64
    }) 
Example #15
Source File: server.py    From Tkinter-GUI-Programming-by-Example with MIT License 5 votes vote down vote up
def get_new_messages():
    data = request.form
    conversation_db_path = get_conversation_db_path_for_users(data)
    conversation_db = Conversation(conversation_db_path)

    timestamp = data["timestamp"]
    requester_username = data["user_one"]

    new_messages = conversation_db.get_new_messages(timestamp, requester_username)

    return jsonify({
        "messages": new_messages
    }) 
Example #16
Source File: server.py    From Tkinter-GUI-Programming-by-Example with MIT License 5 votes vote down vote up
def send_message(username):
    data = request.form
    author = data["author"]
    message = data["message"]
    date_sent = arrow.now().timestamp

    conversation_db_path = get_conversation_db_path_for_users({"user_one": author, "user_two": username})
    conversation = Conversation(conversation_db_path)
    conversation.add_message(author, message, date_sent)

    return jsonify({
        "success": True
    }) 
Example #17
Source File: server.py    From Tkinter-GUI-Programming-by-Example with MIT License 5 votes vote down vote up
def update_avatar(username):
    img_b64 = request.form.get("img_b64")
    database.update_avatar(username, img_b64)

    return jsonify({
        "success": True
    }) 
Example #18
Source File: terraformize_endpoint.py    From terraformize with GNU Lesser General Public License v3.0 5 votes vote down vote up
def health_check() -> Tuple[str, int]:
    """
    A REST endpoint to make sure that terraformize is working

    Returns:
        :return return_body: a JSON of {"healthy": true}
        :return terraform_return_code: 200

    """
    return jsonify({"healthy": True}), 200 
Example #19
Source File: web.py    From svviz with MIT License 5 votes vote down vote up
def _hasPDFExport():
    if export.getExportConverter(dataHub.args, "pdf"):
        return jsonify({"haspdfexport":True})
    return jsonify({"haspdfexport":False}) 
Example #20
Source File: terraformize_endpoint.py    From terraformize with GNU Lesser General Public License v3.0 5 votes vote down vote up
def apply_terraform(module_path: str, workspace_name: str) -> Tuple[str, int]:
    """
    A REST endpoint to apply terraform modules at a given module path inside the main module directory path at a given
    workspace

    Arguments:
        :param module_path:  the name of the subdirectory for the module inside the "terraform_modules_path" to run
        "terraform apply" at
        :param workspace_name: the name of the workspace to run "terraform apply" at

    Returns:
        :return return_body: a JSON of the stdout & stderr from the terraform run
        :return terraform_return_code: the terraform return code

    Exceptions:
        :except FileNotFoundError: will return HTTP 404 with a JSON of the stderr it catch from "terraform init" or
        "terraform apply"
    """
    try:
        terraform_object = Terraformize(workspace_name, configuration["terraform_modules_path"] + "/" + module_path,
                                        terraform_bin_path=configuration["terraform_binary_path"])
        terraform_return_code, terraform_stdout, terraform_stderr = terraform_object.apply(
            request.json, configuration["parallelism"]
        )
        return_body = jsonify({
            "init_stdout": terraform_object.init_stdout,
            "init_stderr": terraform_object.init_stderr,
            "stdout": terraform_stdout,
            "stderr": terraform_stderr
        })
        terraform_return_code = terraform_return_code_to_http_code(int(terraform_return_code))
        return return_body, terraform_return_code
    except FileNotFoundError as error_log:
        return jsonify({"error": str(error_log)}), 404 
Example #21
Source File: webui.py    From MPContribs with MIT License 5 votes vote down vote up
def view(identifier=None, cid_short=None):
    mpfile = read_mpfile_to_view()
    if mpfile is None:
        return render_template("home.html", alert="Choose an MPFile!", session=session)
    fmt = session["options"][0]
    try:
        mpfile_stringio = StringIO(mpfile)
        if identifier is None or cid_short is None:
            response = Response(
                stream_with_context(
                    stream_template(
                        "index.html",
                        session=session,
                        content=process_mpfile(mpfile_stringio, fmt=fmt),
                    )
                )
            )
            response.headers["X-Accel-Buffering"] = "no"
            return response
        else:
            ids = [identifier, cid_short]
            iterator = process_mpfile(mpfile_stringio, fmt=fmt, ids=ids)
            for it in iterator:
                if isinstance(it, list):
                    d = jsonify(it)
            return d
    except Exception:
        pass 
Example #22
Source File: app.py    From Flask-pyoidc with Apache License 2.0 5 votes vote down vote up
def error(error=None, error_description=None):
    return jsonify({'error': error, 'message': error_description}) 
Example #23
Source File: app.py    From Flask-pyoidc with Apache License 2.0 5 votes vote down vote up
def login2():
    user_session = UserSession(flask.session)
    return jsonify(access_token=user_session.access_token,
                   id_token=user_session.id_token,
                   userinfo=user_session.userinfo) 
Example #24
Source File: app.py    From Flask-pyoidc with Apache License 2.0 5 votes vote down vote up
def login1():
    user_session = UserSession(flask.session)
    return jsonify(access_token=user_session.access_token,
                   id_token=user_session.id_token,
                   userinfo=user_session.userinfo) 
Example #25
Source File: views.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def register_by_password_status():
    """AJAX 刷新教务验证状态"""
    if not request.args.get("request", None) or not isinstance(request.args["request"], str):
        return "Invalid request"

    try:
        success, message, identifier = user_service.register_by_password_status_refresh(request.args.get("request"))

        if success:
            # write login state to session
            flash(MSG_REGISTER_SUCCESS)
            if SESSION_PWD_VER_REQ_ID in session:
                del session[SESSION_PWD_VER_REQ_ID]

            _set_current_user(identifier)  # potential uncaught error
            return jsonify({"message": "SUCCESS"})
        elif message in ("PASSWORD_WRONG", "INTERNAL_ERROR", "INVALID_REQUEST_ID"):
            return jsonify({"message": message})
        else:
            return jsonify({"message": "NEXT_TIME"})

    except everyclass.server.user.exceptions.IdentityVerifyRequestNotFoundError:
        return "Invalid request"
    except user_service.IdentityVerifyMethodNotExpectedError:
        return "Invalid request"
    except everyclass.server.user.exceptions.AlreadyRegisteredError:
        # 已经注册成功,但不知为何(可能是网络原因)进入了中间状态,没有执行下面的删除 session 的代码,并且用户刷新页面
        if SESSION_PWD_VER_REQ_ID in session:
            del session[SESSION_PWD_VER_REQ_ID]
        flash(MSG_ALREADY_REGISTERED)
        return redirect(url_for('user.login')) 
Example #26
Source File: views.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def password_strength_check():
    """AJAX 密码强度检查"""
    if request.form.get("password", None):
        # 密码强度检查
        score = user_service.score_password_strength(request.form["password"])
        if score < 2:
            return jsonify({"strong": False,
                            "score": score})
        else:
            return jsonify({"strong": True,
                            "score": score})
    return jsonify({"invalid_request": True}) 
Example #27
Source File: views_main.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def health_check():
    """健康检查"""
    return jsonify({"status": "ok"}) 
Example #28
Source File: ida_service.py    From BASS with 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
Source File: ida_service.py    From BASS with GNU General Public License v2.0 5 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 #30
Source File: ida_service.py    From BASS with 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)