本文整理汇总了Python中werkzeug.datastructures.Headers方法的典型用法代码示例。如果您正苦于以下问题:Python datastructures.Headers方法的具体用法?Python datastructures.Headers怎么用?Python datastructures.Headers使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.datastructures
的用法示例。
在下文中一共展示了datastructures.Headers方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _create_request_from_scope
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def _create_request_from_scope(self, send: Callable) -> Request:
headers = Headers()
headers["Remote-Addr"] = (self.scope.get("client") or ["<local>"])[0]
for name, value in self.scope["headers"]:
headers.add(name.decode("latin1").title(), value.decode("latin1"))
if self.scope["http_version"] < "1.1":
headers.setdefault("Host", self.app.config["SERVER_NAME"] or "")
path = self.scope["path"]
path = path if path[0] == "/" else urlparse(path).path
return self.app.request_class(
self.scope["method"],
self.scope["scheme"],
path,
self.scope["query_string"],
headers,
self.scope.get("root_path", ""),
self.scope["http_version"],
max_content_length=self.app.config["MAX_CONTENT_LENGTH"],
body_timeout=self.app.config["BODY_TIMEOUT"],
send_push_promise=partial(self._send_push_promise, send),
scope=self.scope,
)
示例2: _create_websocket_from_scope
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def _create_websocket_from_scope(self, send: Callable) -> Websocket:
headers = Headers()
headers["Remote-Addr"] = (self.scope.get("client") or ["<local>"])[0]
for name, value in self.scope["headers"]:
headers.add(name.decode("latin1").title(), value.decode("latin1"))
path = self.scope["path"]
path = path if path[0] == "/" else urlparse(path).path
return self.app.websocket_class(
path,
self.scope["query_string"],
self.scope["scheme"],
headers,
self.scope.get("root_path", ""),
self.scope.get("http_version", "1.1"),
self.scope.get("subprotocols", []),
self.queue.get,
partial(self.send_data, send),
partial(self.accept_connection, send),
)
示例3: test_websocket_accept_connection
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def test_websocket_accept_connection(
scope: dict, headers: Headers, subprotocol: Optional[str], has_headers: bool
) -> None:
connection = ASGIWebsocketConnection(Quart(__name__), scope)
mock_send = CoroutineMock()
await connection.accept_connection(mock_send, headers, subprotocol)
if has_headers:
mock_send.assert_called_with(
{
"subprotocol": subprotocol,
"type": "websocket.accept",
"headers": _encode_headers(headers),
}
)
else:
mock_send.assert_called_with({"subprotocol": subprotocol, "type": "websocket.accept"})
示例4: test_request_context_match
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def test_request_context_match() -> None:
app = Quart(__name__)
url_adapter = Mock()
rule = QuartRule("/", methods={"GET"}, endpoint="index")
url_adapter.match.return_value = (rule, {"arg": "value"})
app.create_url_adapter = lambda *_: url_adapter # type: ignore
request = Request(
"GET",
"http",
"/",
b"",
Headers([("host", "quart.com")]),
"",
"1.1",
send_push_promise=no_op_push,
)
RequestContext(app, request)
assert request.url_rule == rule
assert request.view_args == {"arg": "value"}
示例5: test_request_context_matching_error
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def test_request_context_matching_error(
exception_type: Exception, exception_instance: Exception
) -> None:
app = Quart(__name__)
url_adapter = Mock()
url_adapter.match.side_effect = exception_instance
app.create_url_adapter = lambda *_: url_adapter # type: ignore
request = Request(
"GET",
"http",
"/",
b"",
Headers([("host", "quart.com")]),
"",
"1.1",
send_push_promise=no_op_push,
)
RequestContext(app, request)
assert isinstance(request.routing_exception, exception_type) # type: ignore
示例6: test_overlapping_request_ctx
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def test_overlapping_request_ctx() -> None:
app = Quart(__name__)
request = Request(
"GET",
"http",
"/",
b"",
Headers([("host", "quart.com")]),
"",
"1.1",
send_push_promise=no_op_push,
)
ctx1 = app.request_context(request)
await ctx1.__aenter__()
ctx2 = app.request_context(request)
await ctx2.__aenter__()
await ctx1.__aexit__(None, None, None)
assert has_app_context() # Ensure the app context still exists for ctx2
await ctx2.__aexit__(None, None, None)
示例7: test_digest_authorization
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def test_digest_authorization() -> None:
headers = Headers()
headers["Authorization"] = (
"Digest "
'username="identity", '
'realm="realm@rea.lm", '
'nonce="abcd1234", '
'uri="/path", '
'response="abcd1235", '
'opaque="abcd1236"'
)
request = BaseRequestWebsocket("GET", "http", "/", b"", headers, "", "1.1")
auth = request.authorization
assert auth.username == "identity"
assert auth.realm == "realm@rea.lm"
assert auth.nonce == "abcd1234"
assert auth.uri == "/path"
assert auth.response == "abcd1235"
assert auth.opaque == "abcd1236"
示例8: test_request_exceeds_max_content_length
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def test_request_exceeds_max_content_length() -> None:
max_content_length = 5
headers = Headers()
headers["Content-Length"] = str(max_content_length + 1)
request = Request(
"POST",
"http",
"/",
b"",
headers,
"",
"1.1",
max_content_length=max_content_length,
send_push_promise=no_op_push,
)
with pytest.raises(RequestEntityTooLarge):
await request.get_data()
示例9: test_app_handle_request_asyncio_cancelled_error
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def test_app_handle_request_asyncio_cancelled_error() -> None:
app = Quart(__name__)
@app.route("/")
async def index() -> NoReturn:
raise asyncio.CancelledError()
request = app.request_class(
"GET",
"http",
"/",
b"",
Headers([("host", "quart.com")]),
"",
"1.1",
send_push_promise=no_op_push,
)
with pytest.raises(asyncio.CancelledError):
await app.handle_request(request)
示例10: get_download_link
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def get_download_link(book_id, book_format, client):
book_format = book_format.split(".")[0]
book = calibre_db.get_filtered_book(book_id)
if book:
data1 = calibre_db.get_book_format(book.id, book_format.upper())
else:
abort(404)
if data1:
# collect downloaded books only for registered user and not for anonymous user
if current_user.is_authenticated:
ub.update_download(book_id, int(current_user.id))
file_name = book.title
if len(book.authors) > 0:
file_name = book.authors[0].name + '_' + file_name
file_name = get_valid_filename(file_name)
headers = Headers()
headers["Content-Type"] = mimetypes.types_map.get('.' + book_format, "application/octet-stream")
headers["Content-Disposition"] = "attachment; filename=%s.%s; filename*=UTF-8''%s.%s" % (
quote(file_name.encode('utf-8')), book_format, quote(file_name.encode('utf-8')), book_format)
return do_download_file(book, book_format, client, data1, headers)
else:
abort(404)
示例11: rss_proxy_handler
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def rss_proxy_handler(request: WerkzeugRequest) -> WerkzeugResponse:
try:
data = json.loads(request.data.decode('utf-8'))
assert data['token'] == _RSS_PROXY_TOKEN
assert data.get('method') in (None, 'GET', 'POST')
url = urlparse(data['url'])
query = _parse_query(url.query)
assert url.path == '/not-proxy'
assert HTTPHeaders(data['headers'])['user-agent']
except Exception as ex:
LOG.warning(ex, exc_info=ex)
msg = traceback.format_exception_only(type(ex), ex)
return WerkzeugResponse(msg, status=400)
status = query.get('status')
error = query.get('error')
if error:
if error == 'ERROR':
headers = {'x-rss-proxy-status': 'ERROR'}
return WerkzeugResponse(str(status), status=200, headers=headers)
else:
return WerkzeugResponse(str(status), status=int(error))
else:
status = int(status) if status else 200
headers = {'x-rss-proxy-status': status}
return WerkzeugResponse(str(status), status=200, headers=headers)
示例12: testGetSessionWithApiKey
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def testGetSessionWithApiKey(self):
"""Test that an API Key can be used to make requests."""
key = '41'*16
headers = datastructures.Headers()
headers.add('X-SCOREBOARD-API-KEY', key)
with self.client as c:
with self.queryLimit(1):
with mock.patch.object(
models.User, 'get_by_api_key') as getter:
getter.return_value = self.admin_client.user
resp = c.get(self.PATH, headers=headers)
getter.assert_called_once_with(key)
self.assert200(resp)
self.assertEqual(flask.g.user.email, self.admin_client.user.email)
self.assertEqual(flask.g.uid, self.admin_client.user.uid)
self.assertTrue(flask.g.admin)
self.assertEqual(
self.admin_client.user.nick,
resp.json['user']['nick'])
self.assertTrue(resp.json['user']['admin'])
示例13: testGetSessionWithBadApiKey
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def testGetSessionWithBadApiKey(self):
"""Test that an API Key with the wrong value does not work."""
key = '41'*16
for key in ('41'*16, '41'*18, '41'*15, '55'*16, ''):
headers = datastructures.Headers()
headers.add('X-SCOREBOARD-API-KEY', key)
with self.client as c:
with self.queryLimit(1):
with mock.patch.object(
models.User, 'get_by_api_key') as getter:
getter.return_value = None
resp = c.get(self.PATH, headers=headers)
if len(key) == 32:
getter.assert_called_once_with(key)
else:
getter.assert_not_called()
self.assert403(resp)
with self.assertRaises(AttributeError):
_ = flask.g.user
self.assertIsNone(flask.g.uid)
示例14: send_file
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def send_file(self, file_id, content_type, filename, inline=True):
if self.proxy_downloads == ProxyDownloadsMode.local:
return send_file(filename, self.open(file_id), content_type, inline=inline)
try:
bucket, id_ = self._parse_file_id(file_id)
content_disp = 'inline' if inline else 'attachment'
h = Headers()
h.add('Content-Disposition', content_disp, filename=filename)
url = self.client.generate_presigned_url('get_object',
Params={'Bucket': bucket,
'Key': id_,
'ResponseContentDisposition': h.get('Content-Disposition'),
'ResponseContentType': content_type},
ExpiresIn=120)
response = redirect(url)
if self.proxy_downloads == ProxyDownloadsMode.nginx:
# nginx can proxy the request to S3 to avoid exposing the redirect and
# bucket URL to the end user (since it is quite ugly and temporary)
response.headers['X-Accel-Redirect'] = '/.xsf/s3/' + url.replace('://', '/', 1)
return response
except Exception as e:
raise StorageError('Could not send file "{}": {}'.format(file_id, e)), None, sys.exc_info()[2]
示例15: test_auth_decorated_link_good_token_admin_role
# 需要导入模块: from werkzeug import datastructures [as 别名]
# 或者: from werkzeug.datastructures import Headers [as 别名]
def test_auth_decorated_link_good_token_admin_role(client):
user1 = default_config()
user2 = User(name='second user', password='second-pass', roles=['user', 'admin'])
user2.save()
headers = Headers()
headers.set('Authorization', 'Bearer {}'.format(user2.auth_token))
post_data = json.dumps({'current_password': 'some_pass', 'new_password': 'newpass'})
rsp = client.post('/users/{}/change_password'.format(user1.id), data=post_data, headers=headers)
print('\nResponse: {} -> {}'.format(rsp.status, rsp.data.decode()))
assert rsp.status_code == 200, 'should be ok'
assert rsp.json.get('result') == 'Password changed'
# for h in rsp.headers:
# print h
# self.assertTrue('WWW-Authenticate' in rv.headers)
# self.assertTrue('Basic' in rv.headers['WWW-Authenticate'])