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


Python flask.make_response方法代码示例

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


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

示例1: query

# 需要导入模块: import flask [as 别名]
# 或者: from flask import make_response [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

示例2: stream_url

# 需要导入模块: import flask [as 别名]
# 或者: from flask import make_response [as 别名]
def stream_url():
    url = flask.request.args.get('url')
    r = requests.get(url)
    # If it's just an HTML page served over HTTPS, no problem
    if url.startswith('https://') and ( 'text/html' in r.headers['Content-Type'] ):
        return flask.redirect(flask.url_for('redirect_to_url', url=url))

    response = flask.make_response()
    response.data = r.content
    response.headers['Content-Type'] = r.headers['Content-Type']
    # Preserve filename if possible
    if 'Content-Disposition' in r.headers:
        response.headers['Content-Disposition'] = r.headers['Content-Disposition'].replace("attachment;", "inline;")
    # Work around incorrect application/octet-stream
    if 'zenodo.org' in url:
        response.headers['Content-Type'] = 'application/pdf'
    return response 
开发者ID:dissemin,项目名称:oabot,代码行数:19,代码来源:app.py

示例3: api_only

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

示例4: rate_limit

# 需要导入模块: import flask [as 别名]
# 或者: from flask import make_response [as 别名]
def rate_limit(limit, per, scope_func=lambda: request.remote_addr):
    def decorator(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            if current_app.config['USE_RATE_LIMITS']:
                key = 'rate-limit/%s/%s/' % (f.__name__, scope_func())
                limiter = RateLimit(key, limit, per)
                if not limiter.over_limit:
                    rv = f(*args, **kwargs)
                else:
                    rv = too_many_requests('You have exceeded your request rate')
                #rv = make_response(rv)
                g.headers = {
                    'X-RateLimit-Remaining': str(limiter.remaining),
                    'X-RateLimit-Limit': str(limiter.limit),
                    'X-RateLimit-Reset': str(limiter.reset)
                }
                return rv
            else:
                return f(*args, **kwargs)
        return wrapped
    return decorator 
开发者ID:miguelgrinberg,项目名称:api-pycon2014,代码行数:24,代码来源:decorators.py

示例5: etag

# 需要导入模块: import flask [as 别名]
# 或者: from flask import make_response [as 别名]
def etag(f):
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        # only for HEAD and GET requests
        assert request.method in ['HEAD', 'GET'],\
            '@etag is only supported for GET requests'
        rv = f(*args, **kwargs)
        rv = make_response(rv)
        etag = '"' + hashlib.md5(rv.get_data()).hexdigest() + '"'
        rv.headers['ETag'] = etag
        if_match = request.headers.get('If-Match')
        if_none_match = request.headers.get('If-None-Match')
        if if_match:
            etag_list = [tag.strip() for tag in if_match.split(',')]
            if etag not in etag_list and '*' not in etag_list:
                rv = precondition_failed()
        elif if_none_match:
            etag_list = [tag.strip() for tag in if_none_match.split(',')]
            if etag in etag_list or '*' in etag_list:
                rv = not_modified()
        return rv
    return wrapped 
开发者ID:miguelgrinberg,项目名称:api-pycon2014,代码行数:24,代码来源:decorators.py

示例6: person

# 需要导入模块: import flask [as 别名]
# 或者: from flask import make_response [as 别名]
def person():
  limit = min(int(util.param('limit', int) or flask.request.cookies.get('limit') or config.MAX_DB_LIMIT), config.MAX_DB_LIMIT)
  order = util.param('order') or '-stars'
  if 'repo' in order:
    order = '-public_repos'
  elif 'follower' in order:
    order = '-followers'

  person_dbs, person_cursor = model.Account.get_dbs(
      order=order,
      organization=False,
      limit=limit,
    )

  response = flask.make_response(flask.render_template(
    'account/list_person.html',
    title='People',
    description='Top People on GitHub',
    html_class='account-person',
    person_dbs=person_dbs,
    order=order,
    limit=limit,
  ))
  response.set_cookie('limit', str(limit))
  return response 
开发者ID:lipis,项目名称:github-stats,代码行数:27,代码来源:welcome.py

示例7: organization

# 需要导入模块: import flask [as 别名]
# 或者: from flask import make_response [as 别名]
def organization():
  limit = min(int(util.param('limit', int) or flask.request.cookies.get('limit') or config.MAX_DB_LIMIT), config.MAX_DB_LIMIT)
  order = util.param('order') or '-stars'
  if 'repo' in order:
    order = '-public_repos'

  organization_dbs, organization_cursor = model.Account.get_dbs(
      order=order,
      organization=True,
      limit=limit,
    )

  response = flask.make_response(flask.render_template(
    'account/list_organization.html',
    title='Organizations',
    description='Top Organizations on GitHub',
    html_class='account-organization',
    organization_dbs=organization_dbs,
    order=order,
    limit=limit,
  ))
  response.set_cookie('limit', str(limit))
  return response 
开发者ID:lipis,项目名称:github-stats,代码行数:25,代码来源:welcome.py

示例8: do_download_file

# 需要导入模块: import flask [as 别名]
# 或者: from flask import make_response [as 别名]
def do_download_file(book, book_format, client, data, headers):
    if config.config_use_google_drive:
        startTime = time.time()
        df = gd.getFileFromEbooksFolder(book.path, data.name + "." + book_format)
        log.debug('%s', time.time() - startTime)
        if df:
            return gd.do_gdrive_download(df, headers)
        else:
            abort(404)
    else:
        filename = os.path.join(config.config_calibre_dir, book.path)
        if not os.path.isfile(os.path.join(filename, data.name + "." + book_format)):
            # ToDo: improve error handling
            log.error('File not found: %s', os.path.join(filename, data.name + "." + book_format))

        if client == "kobo" and book_format == "kepub":
            headers["Content-Disposition"] = headers["Content-Disposition"].replace(".kepub", ".kepub.epub")

        response = make_response(send_from_directory(filename, data.name + "." + book_format))
        # ToDo Check headers parameter
        for element in headers:
            response.headers[element[0]] = element[1]
        return response

################################## 
开发者ID:janeczku,项目名称:calibre-web,代码行数:27,代码来源:helper.py

示例9: slack_app

# 需要导入模块: import flask [as 别名]
# 或者: from flask import make_response [as 别名]
def slack_app():
    if not signature_verifier.is_valid_request(request.get_data(), request.headers):
        return make_response("invalid request", 403)

    if "command" in request.form \
        and request.form["command"] == "/view":
        trigger_id = request.form["trigger_id"]
        return open_modal(trigger_id)

    elif "payload" in request.form:
        payload = json.loads(request.form["payload"])
        if payload["type"] == "view_submission" \
            and payload["view"]["callback_id"] == "modal-id":
            submitted_data = payload["view"]["state"]["values"]
            print(submitted_data)  # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}}
            return make_response("", 200)
        if payload["type"] == "shortcut" \
            and payload["callback_id"] == "view-test":
            return open_modal(payload["trigger_id"])

    return make_response("", 404) 
开发者ID:slackapi,项目名称:python-slackclient,代码行数:23,代码来源:views_default_to_current_conversation.py

示例10: per_request

# 需要导入模块: import flask [as 别名]
# 或者: from flask import make_response [as 别名]
def per_request():
    try:
        client = WebClient(
            token=os.environ["SLACK_BOT_TOKEN"],
            run_async=False
        )
        response = client.chat_postMessage(
            channel="#random",
            text="You used a new WebClient for posting this message!"
        )
        return str(response)
    except SlackApiError as e:
        return make_response(str(e), 400)


# This doesn't work 
开发者ID:slackapi,项目名称:python-slackclient,代码行数:18,代码来源:issue_497.py

示例11: per_request_async

# 需要导入模块: import flask [as 别名]
# 或者: from flask import make_response [as 别名]
def per_request_async():
    try:
        # This is not optimal and the host should have a large number of FD (File Descriptor)
        loop_for_this_request = asyncio.new_event_loop()

        async_client = WebClient(
            token=os.environ["SLACK_BOT_TOKEN"],
            run_async=True,
            loop=loop_for_this_request
        )
        future = async_client.chat_postMessage(
            channel="#random",
            text="You used the singleton WebClient for posting this message!"
        )
        response = loop_for_this_request.run_until_complete(future)
        return str(response)
    except SlackApiError as e:
        return make_response(str(e), 400) 
开发者ID:slackapi,项目名称:python-slackclient,代码行数:20,代码来源:issue_497.py

示例12: job_create

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

示例13: job_get_status

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

示例14: job_add_sample

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

示例15: job_submit

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


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