本文整理汇总了Python中werkzeug.wrappers.Response方法的典型用法代码示例。如果您正苦于以下问题:Python wrappers.Response方法的具体用法?Python wrappers.Response怎么用?Python wrappers.Response使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.wrappers
的用法示例。
在下文中一共展示了wrappers.Response方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: api_only
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import 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
示例2: application
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def application(request):
file_path = request.path.lstrip(URL_PREFIX)
full_path = os.path.join(BASE_PATH, file_path)
# Protect against path traversal attacks, if they make it this far.
if not full_path.startswith(BASE_PATH):
# DANGER!
return Response("Suspicious url", status=403)
format = request.args.get('format', None)
if format == 'raw':
# Let nginx serve raw files
accel_path = os.path.join('/accelredir/', file_path)
return Response('', headers={'X-Accel-Redirect': accel_path})
try:
extension = get_extension(full_path, format)
if extension and extension in handlers:
return handlers[extension](full_path, format)
else:
return Response("No handlers for format %s" % extension, status=400)
except FileNotFoundError:
return Response("Not found", status=404)
return Response(full_path)
示例3: abort
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def abort(status, *args, **kwargs):
'''
Raises an :py:exc:`HTTPException` for the given status code or WSGI
application::
abort(404) # 404 Not Found
abort(Response('Hello World'))
Can be passed a WSGI application or a status code. If a status code is
given it's looked up in the list of exceptions and will raise that
exception, if passed a WSGI application it will wrap it in a proxy WSGI
exception and raise that::
abort(404)
abort(Response('Hello World'))
'''
return _aborter(status, *args, **kwargs)
示例4: single_serve
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def single_serve(message=None, port=5000):
import logging
from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
captured = {}
def application(environ, start_response):
request = Request(environ)
request.environ.get('werkzeug.server.shutdown')()
captured.update(dict(request.args.items()))
if message:
print(message)
response = Response(message, mimetype='text/plain')
return response(environ, start_response)
run_simple('localhost', port, application)
return captured
示例5: __call__
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def __call__(self, environ, start_response):
if _ENABLE_TEST:
global current_environ
current_environ = environ
self.parse_header(environ)
app_params = environ["_app_params"]
if not any(app_params.values()): # all app_params's value is None
self.parse_body(environ)
unauth_response = Response(
json.dumps({"code": 401, "error": "Unauthorized."}),
status=401,
mimetype="application/json",
)
if app_params["id"] is None:
return unauth_response(environ, start_response)
if (APP_ID == app_params["id"]) and (
app_params["key"] in [MASTER_KEY, APP_KEY, ANDX_KEY]
):
return self.app(environ, start_response)
if (APP_ID == app_params["id"]) and (app_params["master_key"] == MASTER_KEY):
return self.app(environ, start_response)
return unauth_response(environ, start_response)
示例6: test_webob_response_normalization
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def test_webob_response_normalization(httpbin):
import webob
raw_request = webob.Request.blank(httpbin.url + '/get')
raw_request.query_string = 'key=val'
raw_request.method = 'GET'
raw_request.content_type = 'application/json'
raw_response = webob.Response()
raw_response.content_type = 'application/json'
response = normalize_response(raw_response, raw_request)
assert response.path == '/get'
assert response.content_type == 'application/json'
assert response.url == httpbin.url + '/get?key=val'
assert response.status_code == '200'
示例7: test_werkzeug_response_normalization
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def test_werkzeug_response_normalization(httpbin):
from werkzeug.wrappers import Request, Response
from werkzeug.test import create_environ
raw_request = Request(create_environ(
path='/get',
base_url=httpbin.url,
query_string='key=val',
method='GET',
))
raw_response = Response(
response=b'{"key2": "val2"}',
content_type='application/json',
)
response = normalize_response(raw_response, raw_request)
assert response.path == '/get'
assert response.content_type == 'application/json'
assert response.url == httpbin.url + '/get?key=val'
assert response.status_code == '200'
示例8: on_pve
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def on_pve(self, module='default', target='localhost'):
"""
Request handler for /pve route
"""
if module in self._config:
start = time.time()
output = collect_pve(self._config[module], target)
response = Response(output)
response.headers['content-type'] = CONTENT_TYPE_LATEST
self._duration.labels(module).observe(time.time() - start)
else:
response = Response("Module '{0}' not found in config".format(module))
response.status_code = 400
return response
示例9: on_index
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def on_index(self):
"""
Request handler for index route (/).
"""
response = Response(
"""<html>
<head><title>Proxmox VE Exporter</title></head>
<body>
<h1>Proxmox VE Exporter</h1>
<p>Visit <code>/pve?target=1.2.3.4</code> to use.</p>
</body>
</html>"""
)
response.headers['content-type'] = 'text/html'
return response
示例10: _do_test_client_retry_429
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def _do_test_client_retry_429(httpserver, retry_after, expected_seconds):
records = []
def record_date(_):
records.append(datetime.datetime.utcnow())
return Response("It works now !", 200)
httpserver.expect_oneshot_request("/").respond_with_data(
"This is an 429 error", status=429, headers={"Retry-After": retry_after}
)
httpserver.expect_request("/").respond_with_handler(record_date)
with http.Client() as client:
now = datetime.datetime.utcnow()
client.get(httpserver.url_for("/"))
assert len(httpserver.log) == 2
elapsed_seconds = (records[0] - now).total_seconds()
assert expected_seconds - 1 < elapsed_seconds <= expected_seconds + 1
httpserver.check_assertions()
示例11: callback
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def callback(self, session: Dict, request: Request) -> Response:
""" Authentication callback handler """
# validate state
state = request.args.get("state", "unknown")
_state = session.pop("state", None)
if state != _state:
return Response("Invalid state", status=403)
# fetch user tokens
code: str = request.args.get("code", "unknown")
tokens = self.kc.callback(code)
session["tokens"] = json.dumps(tokens)
# fetch user info
access_token = tokens["access_token"]
user = self.kc.fetch_userinfo(access_token)
session["user"] = json.dumps(user)
return redirect(self.redirect_uri)
示例12: requires_auth
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
state = is_authorized()
if state is False:
if request.path.startswith('/api'):
return api_response(400, message="Invalid authentication.")
return redirect(internal_url_for('/login'))
if isinstance(state, Response):
return state
return f(*args, **kwargs)
return decorated
示例13: fallbackRender
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def fallbackRender(template, key=None):
def wrapper(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
resp = fn(*args, **kwargs)
if isinstance(resp, ResponseBase):
return resp
data, code, headers = unpack(resp)
accepted = set(request.accept_mimetypes.values())
explicit = not (not request.args.get("json", False))
if len(accepted & API_MIMETYPES) or explicit:
# 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)
ct = 'application/json'
else:
resp = make_response(render_template(template,
key=key,
data=data),
code)
ct = "text/html"
if headers:
resp.headers.update(headers)
resp.headers["Content-Type"] = ct
return resp
return decorated_view
return wrapper
示例14: card
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def card(name: str) -> wrappers.Response:
return redirect('https://pennydreadfulmagic.com/cards/{name}/'.format(name=name))
示例15: old_charts
# 需要导入模块: from werkzeug import wrappers [as 别名]
# 或者: from werkzeug.wrappers import Response [as 别名]
def old_charts() -> Response:
return redirect(url_for('charts'))