本文整理汇总了Python中starlette.requests.Request方法的典型用法代码示例。如果您正苦于以下问题:Python requests.Request方法的具体用法?Python requests.Request怎么用?Python requests.Request使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类starlette.requests
的用法示例。
在下文中一共展示了requests.Request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dispatch
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
method = request.method
path_template, is_handled_path = self.get_path_template(request)
if self._is_path_filtered(is_handled_path):
return await call_next(request)
REQUESTS_IN_PROGRESS.labels(method=method, path_template=path_template).inc()
REQUESTS.labels(method=method, path_template=path_template).inc()
try:
before_time = time.perf_counter()
response = await call_next(request)
after_time = time.perf_counter()
except Exception as e:
EXCEPTIONS.labels(method=method, path_template=path_template, exception_type=type(e).__name__).inc()
raise e from None
else:
REQUESTS_PROCESSING_TIME.labels(method=method, path_template=path_template).observe(
after_time - before_time
)
RESPONSES.labels(method=method, path_template=path_template, status_code=response.status_code).inc()
finally:
REQUESTS_IN_PROGRESS.labels(method=method, path_template=path_template).dec()
return response
示例2: graphql_http_server
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def graphql_http_server(self, request: Request) -> Response:
try:
data = await self.extract_data_from_request(request)
except HttpError as error:
return PlainTextResponse(error.message or error.status, status_code=400)
context_value = await self.get_context_for_request(request)
extensions = await self.get_extensions_for_request(request, context_value)
middleware = await self.get_middleware_for_request(request, context_value)
success, response = await graphql(
self.schema,
data,
context_value=context_value,
root_value=self.root_value,
validation_rules=self.validation_rules,
debug=self.debug,
introspection=self.introspection,
logger=self.logger,
error_formatter=self.error_formatter,
extensions=extensions,
middleware=middleware,
)
status_code = 200 if success else 400
return JSONResponse(response, status_code=status_code)
示例3: debug_python
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def debug_python(request: Request):
body = await request.body()
if request.headers.get("content-transfer-encoding") == "base64":
# TODO: decode base64
pass
resp = {"code": 0, "message": "success", "result": ""}
try:
with stdout_io() as s:
exec(body, globals())
output = s.getvalue()
resp["result"] = output
except Exception as ex:
resp["code"] = 1
resp["message"] = "fail"
resp["result"] = str(ex)
logger.error(resp)
return resp
示例4: test_permissions_dependency_as_class
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def test_permissions_dependency_as_class(dumb_request):
class FailPermission(BasePermission):
def has_required_permisions(self, request: Request) -> bool:
return False
class AllowPermission(BasePermission):
def has_required_permisions(self, request: Request) -> bool:
return True
dependency = PermissionsDependency(permissions_classes=[AllowPermission])
dependency(request=dumb_request)
dependency = PermissionsDependency(
permissions_classes=[AllowPermission, FailPermission])
with pytest.raises(HTTPException) as excinfo:
dependency(request=dumb_request)
assert excinfo.value.status_code == status.HTTP_403_FORBIDDEN
assert excinfo.value.detail == "Forbidden."
示例5: test_paginate_equal_offset_limit
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def test_paginate_equal_offset_limit():
from fastapi_contrib.db.client import MongoDBClient
MongoDBClient.__instance = None
MongoDBClient._MongoDBClient__instance = None
dumb_request = Request(
{
"type": "http",
"method": "GET",
"path": "/",
"query_string": b"limit=10&offset=10",
"headers": {},
}
)
pagination = Pagination(request=dumb_request, limit=10, offset=10)
assert pagination.limit == 10
assert pagination.offset == 10
resp = await pagination.paginate(serializer_class=TestSerializer)
assert resp == {
"count": 1,
"next": None,
"previous": "/?limit=10",
"result": [{"id": 1}],
}
示例6: test_paginate_offset_less_than_limit
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def test_paginate_offset_less_than_limit():
from fastapi_contrib.db.client import MongoDBClient
MongoDBClient.__instance = None
MongoDBClient._MongoDBClient__instance = None
dumb_request = Request(
{
"type": "http",
"method": "GET",
"path": "/",
"query_string": b"limit=10&offset=0",
"headers": {},
}
)
pagination = Pagination(request=dumb_request, limit=10, offset=0)
assert pagination.limit == 10
assert pagination.offset == 0
resp = await pagination.paginate(serializer_class=TestSerializer)
assert resp == {
"count": 1,
"next": None,
"previous": None,
"result": [{"id": 1}],
}
示例7: test_paginate_limit_less_than_offset
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def test_paginate_limit_less_than_offset():
from fastapi_contrib.db.client import MongoDBClient
MongoDBClient.__instance = None
MongoDBClient._MongoDBClient__instance = None
dumb_request = Request(
{
"type": "http",
"method": "GET",
"path": "/",
"query_string": b"limit=1&offset=10",
"headers": {},
}
)
pagination = Pagination(request=dumb_request, limit=1, offset=10)
assert pagination.limit == 1
assert pagination.offset == 10
resp = await pagination.paginate(serializer_class=TestSerializer)
assert resp == {
"count": 1,
"next": None,
"previous": "/?limit=1&offset=9",
"result": [{"id": 1}],
}
示例8: test_paginate_offset_with_additional_query_params
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def test_paginate_offset_with_additional_query_params():
from fastapi_contrib.db.client import MongoDBClient
MongoDBClient.__instance = None
MongoDBClient._MongoDBClient__instance = None
dumb_request = Request(
{
"type": "http",
"method": "GET",
"path": "/",
"query_string": b"additional=15&limit=0&offset=0",
"headers": {},
}
)
pagination = Pagination(request=dumb_request, limit=0, offset=0)
assert pagination.limit == 0
assert pagination.offset == 0
resp = await pagination.paginate(serializer_class=TestSerializer)
assert resp == {
"count": 1,
"next": "/?additional=15&limit=0&offset=0",
"previous": None,
"result": [{"id": 1}],
}
示例9: __new__
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def __new__(mcs, name, bases, namespace, *args, **kwargs):
cls = super(PaginationMeta, mcs).__new__(mcs, name, bases, namespace)
_cls__init__ = cls.__init__
def __init__(
self,
request: Request,
offset: int = Query(
default=cls.default_offset, ge=0, le=cls.max_offset
),
limit: int = Query(
default=cls.default_limit, ge=1, le=cls.max_limit
),
):
_cls__init__(self, request, offset, limit)
setattr(cls, "__init__", __init__)
return cls
示例10: http_exception_handler
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def http_exception_handler(
request: Request, exc: StarletteHTTPException
) -> UJSONResponse:
"""
Handles StarletteHTTPException, translating it into flat dict error data:
* code - unique code of the error in the system
* detail - general description of the error
* fields - list of dicts with description of the error in each field
:param request: Starlette Request instance
:param exc: StarletteHTTPException instance
:return: UJSONResponse with newly formatted error data
"""
fields = getattr(exc, "fields", [])
message = getattr(exc, "detail", "Validation error.")
if message and not any(
[message.endswith("."), message.endswith("?"), message.endswith("!")]
):
message = message + "."
data = {
"error_codes": [getattr(exc, "error_code", exc.status_code)],
"message": message,
"fields": fields,
}
return UJSONResponse(data, status_code=exc.status_code)
示例11: before_request
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def before_request(request: Request, tracer):
"""
Gather various info about the request and start new span with the data.
"""
span_context = tracer.extract(
format=Format.HTTP_HEADERS, carrier=request.headers
)
span = tracer.start_span(
operation_name=f"{request.method} {request.url.path}",
child_of=span_context,
)
span.set_tag("http.url", str(request.url))
remote_ip = request.client.host
span.set_tag(tags.PEER_HOST_IPV4, remote_ip or "")
remote_port = request.client.port
span.set_tag(tags.PEER_PORT, remote_port or "")
return span
示例12: dispatch
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def dispatch(self, request: Request, call_next: Any) -> Response:
"""
Store span in some request.state storage using Tracer.scope_manager,
using the returned `Scope` as Context Manager to ensure
`Span` will be cleared and (in this case) `Span.finish()` be called.
:param request: Starlette's Request object
:param call_next: Next callable Middleware in chain or final view
:return: Starlette's Response object
"""
tracer = request.app.tracer
span = self.before_request(request, tracer)
with tracer.scope_manager.activate(span, True) as scope:
request_span.set(span)
request.state.opentracing_span = span
request.state.opentracing_scope = scope
request.state.opentracing_tracer = tracer
response = await call_next(request)
return response
示例13: authentification
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def authentification(request: requests.Request):
# Only SHA1 is supported
header_signature = request.headers.get("X-Hub-Signature")
if header_signature is None:
LOG.warning("Webhook without signature")
raise fastapi.HTTPException(status_code=403)
try:
sha_name, signature = header_signature.split("=")
except ValueError:
sha_name = None
if sha_name != "sha1":
LOG.warning("Webhook signature malformed")
raise fastapi.HTTPException(status_code=403)
body = await request.body()
mac = utils.compute_hmac(body)
if not hmac.compare_digest(mac, str(signature)):
LOG.warning("Webhook signature invalid")
raise fastapi.HTTPException(status_code=403)
示例14: simulator_authentification
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def simulator_authentification(request: requests.Request):
authorization = request.headers.get("Authorization")
if authorization:
if authorization.startswith("token "):
try:
options = http.DEFAULT_CLIENT_OPTIONS.copy()
options["headers"]["Authorization"] = authorization
async with http.AsyncClient(
base_url=config.GITHUB_API_URL, **options
) as client:
await client.get("/user")
except http.HTTPError as e:
raise fastapi.HTTPException(status_code=e.response.status_code)
else:
raise fastapi.HTTPException(status_code=403)
else:
await authentification(request)
示例15: simulator
# 需要导入模块: from starlette import requests [as 别名]
# 或者: from starlette.requests import Request [as 别名]
def simulator(request: requests.Request):
token = request.headers.get("Authorization")
if token:
token = token[6:] # Drop 'token '
data = SimulatorSchema(await request.json())
if data["pull_request"]:
loop = asyncio.get_running_loop()
title, summary = await loop.run_in_executor(
None,
functools.partial(
_sync_simulator,
data["mergify.yml"]["pull_request_rules"],
*data["pull_request"],
token=token,
),
)
else:
title, summary = ("The configuration is valid", None)
return responses.JSONResponse(
status_code=200, content={"title": title, "summary": summary}
)