本文整理汇总了Python中flask.Response方法的典型用法代码示例。如果您正苦于以下问题:Python flask.Response方法的具体用法?Python flask.Response怎么用?Python flask.Response使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask
的用法示例。
在下文中一共展示了flask.Response方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_authentication_response
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def check_authentication_response() -> Union[Response, None]:
"""
Return the response as per the authentication requirements.
"""
if get_authentication():
if get_token():
token = check_token(request, get_session())
if not token:
if request.authorization is None:
return failed_authentication(False)
else:
return verify_user()
elif request.authorization is None:
return failed_authentication(False)
else:
return verify_user()
else:
return None
示例2: exit_maintenance
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def exit_maintenance():
config = get_config()
auth = request.authorization
if auth \
and auth.username in config.MAINTENANCE_CREDENTIALS \
and config.MAINTENANCE_CREDENTIALS[auth.username] == auth.password:
try:
os.remove(config.MAINTENANCE_FILE) # remove maintenance file
except OSError:
return 'Not in maintenance mode. Ignore command.'
open(os.path.join(os.getcwd(), 'reload'), "w+").close() # uwsgi reload
return 'success'
else:
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
示例3: custom_prior_redirect_func
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def custom_prior_redirect_func(request, parse):
"""
用于在 prior_request_redirect 阶段的自定义重定向
若返回一个 flask.Response 对象, 则执行重定向, 直接返回这个 Response
若返回None, 则不进行重定向
不应该修改parse变量 (添加头和cookie除外)
详见 `config_default.py` 中 `Custom Redirection` 部分
:param request: flask request object
:type request: Request
:param parse: the zmirror parse variable
:type parse: ZmirrorThreadLocal
:rtype: Union[Response, None]
"""
print(request.url, parse.remote_url)
from flask import redirect
# 如果你想重定向, 请使用这句
# return redirect("/location/you/want/redirect/to")
return None # 不进行自定义重定向
示例4: try_get_cached_response
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def try_get_cached_response(url, client_header=None):
"""
尝试从本地缓存中取出响应
:param url: real url with query string
:type client_header: dict
:rtype: Union[Response, None]
"""
# Only use cache when client use GET
if local_cache_enable and parse.method == 'GET' and cache.is_cached(url):
if client_header is not None and 'if-modified-since' in client_header and \
cache.is_unchanged(url, client_header.get('if-modified-since', None)):
dbgprint('FileCacheHit-304', url)
return generate_304_response()
else:
cached_info = cache.get_info(url)
if cached_info.get('without_content', True):
# 关于 without_content 的解释, 请看update_content_in_local_cache()函数
return None
# dbgprint('FileCacheHit-200')
resp = cache.get_obj(url)
assert isinstance(resp, Response)
parse.set_extra_resp_header('x-zmirror-cache', 'FileHit')
return resp
else:
return None
示例5: generate_our_response
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def generate_our_response():
"""
生成我们的响应
:rtype: Response
"""
# copy and parse remote response
resp = copy_response(is_streamed=parse.streamed_our_response)
if parse.time["req_time_header"] >= 0.00001:
parse.set_extra_resp_header('X-Header-Req-Time', "%.4f" % parse.time["req_time_header"])
if parse.time.get("start_time") is not None and not parse.streamed_our_response:
# remote request time should be excluded when calculating total time
parse.set_extra_resp_header('X-Body-Req-Time', "%.4f" % parse.time["req_time_body"])
parse.set_extra_resp_header('X-Compute-Time',
"%.4f" % (process_time() - parse.time["start_time"]))
parse.set_extra_resp_header('X-Powered-By', 'zmirror/%s' % CONSTS.__VERSION__)
if developer_dump_all_traffics and not parse.streamed_our_response:
dump_zmirror_snapshot("traffic")
return resp
示例6: make_web
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def make_web(queue):
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
def gen():
while True:
frame = queue.get()
_, frame = cv2.imencode('.JPEG', frame)
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame.tostring() + b'\r\n')
@app.route('/video_feed')
def video_feed():
return Response(gen(),
mimetype='multipart/x-mixed-replace; boundary=frame')
try:
app.run(host='0.0.0.0', port=8889)
except:
print('unable to open port')
示例7: messages
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def messages():
"""Main bot message handler."""
if "application/json" in request.headers["Content-Type"]:
body = request.json
else:
return Response(status=415)
activity = Activity().deserialize(body)
auth_header = (
request.headers["Authorization"] if "Authorization" in request.headers else ""
)
async def aux_func(turn_context):
await BOT.on_turn(turn_context)
try:
task = LOOP.create_task(
ADAPTER.process_activity(activity, auth_header, aux_func)
)
LOOP.run_until_complete(task)
return Response(status=201)
except Exception as exception:
raise exception
示例8: messages
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def messages():
# Main bot message handler.
if "application/json" in request.headers["Content-Type"]:
body = request.json
else:
return Response(status=415)
activity = Activity().deserialize(body)
auth_header = (
request.headers["Authorization"] if "Authorization" in request.headers else ""
)
try:
task = LOOP.create_task(
ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
)
LOOP.run_until_complete(task)
return Response(status=201)
except Exception as exception:
raise exception
示例9: __init__
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def __init__(self, response, status=None, headers=None, **kwargs):
""" Init a JSON response
:param response: Response data
:type response: *
:param status: Status code
:type status: int|None
:param headers: Additional headers
:type headers: dict|None
"""
# Store response
self._response_data = self.preprocess_response_data(response)
# PrettyPrint?
try:
indent = 2 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr else None
except RuntimeError: # "RuntimeError: working outside of application context"
indent = None
# Init super
super(JsonResponse, self).__init__(
json.dumps(self._response_data, indent=indent),
headers=headers, status=status, mimetype='application/json',
direct_passthrough=True, **kwargs)
示例10: dump_result
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def dump_result(project, _format):
resultdb = app.config['resultdb']
# force update project list
resultdb.get(project, 'any')
if project not in resultdb.projects:
return "no such project.", 404
offset = int(request.args.get('offset', 0)) or None
limit = int(request.args.get('limit', 0)) or None
results = resultdb.select(project, offset=offset, limit=limit)
if _format == 'json':
valid = request.args.get('style', 'rows') == 'full'
return Response(result_dump.dump_as_json(results, valid),
mimetype='application/json')
elif _format == 'txt':
return Response(result_dump.dump_as_txt(results),
mimetype='text/plain')
elif _format == 'csv':
return Response(result_dump.dump_as_csv(results),
mimetype='text/csv')
示例11: do_export
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def do_export():
format = request.form.get("format", "svg").lower()
session["last_format"] = format
filename = "export.{}".format(format)
svg = dataHub.trackCompositor.render()
converter = export.getExportConverter(dataHub.args, format)
if format == "svg":
mimetype = "image/svg+xml"
data = svg
elif format == "png":
mimetype = "image/png"
data = export.convertSVG(svg, "png", converter)
elif format == "pdf":
mimetype = "application/pdf"
data = export.convertSVG(svg, "pdf", converter)
else:
raise Exception("unknown format")
response = Response(data,
mimetype=mimetype,
headers={"Content-Disposition": "attachment;filename={}".format(filename)})
return response
示例12: displayIsizes
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def displayIsizes(name):
if not dataHub.samples[name].insertSizePlot:
return None
return Response(dataHub.samples[name].insertSizePlot, mimetype="image/png")
示例13: get_dotplot
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def get_dotplot(name):
if name in dataHub.dotplots:
return Response(dataHub.dotplots[name], mimetype="image/png")
return None
示例14: get
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [as 别名]
def get(self) -> Response:
"""Return main entrypoint for the api."""
return set_response_headers(jsonify(get_doc().entrypoint.get()))
示例15: delete
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Response [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)