当前位置: 首页>>代码示例>>Python>>正文


Python flask.jsonify方法代码示例

本文整理汇总了Python中flask.jsonify方法的典型用法代码示例。如果您正苦于以下问题:Python flask.jsonify方法的具体用法?Python flask.jsonify怎么用?Python flask.jsonify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在flask的用法示例。


在下文中一共展示了flask.jsonify方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: upload

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
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 
开发者ID:toolforge,项目名称:video2commons,代码行数:25,代码来源:upload.py

示例2: whitelist_add

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
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") 
开发者ID:Cisco-Talos,项目名称:BASS,代码行数:21,代码来源:server.py

示例3: query

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
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 ### 
开发者ID:CLARIAH,项目名称:grlc,代码行数:22,代码来源:server.py

示例4: getResponseText

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
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] 
开发者ID:CLARIAH,项目名称:grlc,代码行数:26,代码来源:sparql.py

示例5: run

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
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 
开发者ID:gradiuscypher,项目名称:bounty_tools,代码行数:27,代码来源:reconng.py

示例6: _hasPDFExport

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
def _hasPDFExport():
    if export.getExportConverter(dataHub.args, "pdf"):
        return jsonify({"haspdfexport":True})
    return jsonify({"haspdfexport":False}) 
开发者ID:svviz,项目名称:svviz,代码行数:6,代码来源:web.py

示例7: _hasPNGExport

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
def _hasPNGExport():
    if export.getExportConverter(dataHub.args, "png"):
        return jsonify({"haspngexport":True})
    return jsonify({"haspngexport":False}) 
开发者ID:svviz,项目名称:svviz,代码行数:6,代码来源:web.py

示例8: display

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
def display():
    req = request.args.get('req', 0)

    if req == "progress":
        return jsonify(result="done")

    if req in ["alt", "ref", "amb"]:
        allele = req
        results = []
        for name, sample in dataHub.samples.items():
            # svg = open("{}.{}.svg".format(req, name)).read()
            track = sample.tracks[allele]
            track.render()
            svg = track.svg.asString("web")
            results.append({"name":name, "svg":svg})

        for annotation in dataHub.alleleTracks[allele]:
            track = dataHub.alleleTracks[allele][annotation]
            track.render(spacing=5)
            annoSVG = track.svg.asString("web")
            results.append({"name":annotation, "svg":annoSVG})

        return jsonify(results=results)


    if req == "counts":
        return jsonify(result=dataHub.getCounts())

    return jsonify(result="unknown request: {}".format(req)) 
开发者ID:svviz,项目名称:svviz,代码行数:31,代码来源:web.py

示例9: get

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
def get(self) -> Response:
        """Return main entrypoint for the api."""
        return set_response_headers(jsonify(get_doc().entrypoint.get())) 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:5,代码来源:resources.py

示例10: delete

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
def delete(self, id_: str, path: str) -> Response:
        """Delete object with id=id_ from database."""
        id_ = str(id_)
        auth_response = check_authentication_response()
        if isinstance(auth_response, Response):
            return auth_response

        class_type = get_doc().collections[path]["collection"].class_.title
        # Get path of the collection-class
        class_path = get_doc().collections[path]["collection"].class_.path

        if checkClassOp(class_path, "DELETE"):
            # Check if class_type supports PUT operation
            try:
                # Delete the Item with ID == id_
                crud.delete(id_, class_type, session=get_session())
                method = "DELETE"
                resource_url = "{}{}/{}/{}".format(
                    get_hydrus_server_url(), get_api_name(), path, id_)
                last_job_id = crud.get_last_modification_job_id(session=get_session())
                new_job_id = crud.insert_modification_record(method, resource_url,
                                                             session=get_session())
                send_sync_update(socketio=socketio, new_job_id=new_job_id,
                                 last_job_id=last_job_id, method=method,
                                 resource_url=resource_url)
                status_description = "Object with ID {} successfully deleted".format(id_)
                status = HydraStatus(code=200, title="Object successfully deleted.",
                                     desc=status_description)
                return set_response_headers(jsonify(status.generate()))

            except (ClassNotFound, InstanceNotFound) as e:
                error = e.get_HTTP()
                return set_response_headers(jsonify(error.generate()), status_code=error.code)

        abort(405) 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:37,代码来源:resources.py

示例11: token_response

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
def token_response(token: str) -> Response:
    """
    Return succesful token generation object
    """
    message = {200: "User token generated"}
    response = set_response_headers(jsonify(message), status_code=200,
                                    headers=[{'X-Authorization': token}])
    return response 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:10,代码来源:auth.py

示例12: failed_authentication

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
def failed_authentication(incorrect: bool) -> Response:
    """
    Return failed authentication object.
    """
    if not incorrect:
        message = {401: "Need credentials to authenticate"}
        realm = 'Basic realm="Login required"'
    else:
        message = {401: "Incorrect credentials"}
        realm = 'Basic realm="Incorrect credentials"'
    nonce = create_nonce(get_session())
    response = set_response_headers(jsonify(message), status_code=401,
                                    headers=[{'WWW-Authenticate': realm},
                                             {'X-Authentication': nonce}])
    return response 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:17,代码来源:auth.py

示例13: verify_user

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
def verify_user() -> Union[Response, None]:
    """
    Verify the credentials of the user and assign token.
    """
    try:
        auth = check_authorization(request, get_session())
        if auth is False:
            return failed_authentication(True)
        elif get_token():
            token = add_token(request, get_session())
            return token_response(token)
    except Exception as e:
        error = e.get_HTTP()  # type: HydraError
        return set_response_headers(jsonify(error.generate()), status_code=error.code)
    return None 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:17,代码来源:auth.py

示例14: get_devices

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
def get_devices():
    return jsonify({'device': [device.get_url() 
                               for device in Device.query.all()]}) 
开发者ID:PacktPublishing,项目名称:Mastering-Python-Networking-Second-Edition,代码行数:5,代码来源:chapter9_6.py

示例15: get_device

# 需要导入模块: import flask [as 别名]
# 或者: from flask import jsonify [as 别名]
def get_device(id):
    return jsonify(Device.query.get_or_404(id).export_data()) 
开发者ID:PacktPublishing,项目名称:Mastering-Python-Networking-Second-Edition,代码行数:4,代码来源:chapter9_6.py


注:本文中的flask.jsonify方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。