本文整理汇总了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 ###
示例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
示例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
示例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
示例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
示例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
示例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
示例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
##################################
示例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)
示例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
示例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)
示例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)
示例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)
示例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)
示例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)