本文整理匯總了Python中sanic.request.Request方法的典型用法代碼示例。如果您正苦於以下問題:Python request.Request方法的具體用法?Python request.Request怎麽用?Python request.Request使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sanic.request
的用法示例。
在下文中一共展示了request.Request方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: request_timeout_callback
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def request_timeout_callback(self):
# See the docstring in the RequestTimeout exception, to see
# exactly what this timeout is checking for.
# Check if elapsed time since request initiated exceeds our
# configured maximum request timeout value
time_elapsed = time() - self._last_request_time
if time_elapsed < self.request_timeout:
time_left = self.request_timeout - time_elapsed
self._request_timeout_handler = self.loop.call_later(
time_left, self.request_timeout_callback
)
else:
if self._request_stream_task:
self._request_stream_task.cancel()
if self._request_handler_task:
self._request_handler_task.cancel()
self.write_error(RequestTimeout("Request Timeout"))
示例2: data_received
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def data_received(self, data):
# Check for the request itself getting too large and exceeding
# memory limits
self._total_request_size += len(data)
if self._total_request_size > self.request_max_size:
self.write_error(PayloadTooLarge("Payload Too Large"))
# Create parser if this is the first time we're receiving data
if self.parser is None:
assert self.request is None
self.headers = []
self.parser = HttpRequestParser(self)
# requests count
self.state["requests_count"] = self.state["requests_count"] + 1
# Parse request chunk or close connection
try:
self.parser.feed_data(data)
except HttpParserError:
message = "Bad Request"
if self.app.debug:
message += "\n" + traceback.format_exc()
self.write_error(InvalidUsage(message))
示例3: get_plist
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def get_plist(request: Request, app_id: int, package_id: str):
"""
獲取iPhone在線安裝ipa需要的plist
:param request:
:param app_id: app的id
:param package_id: 安裝包的id
:return:
"""
session = Session()
# 檢查是否存在該app
app_query = DB.model_exists(session, AppModel, id=app_id, type=AppType.iOS)
if not app_query:
raise BadRequest('not find app id: {}'.format(app_id))
# 檢查app是否存在該版本
app_version_query = DB.model_exists(session, AppVersionModel, app_id=app_id, id=package_id)
if not app_version_query:
raise BadRequest('not find version id: {} by app id: {}'.format(package_id, app_id))
app = app_query.one()
app_version = app_version_query.one()
return text(IPAPlist.parse(app_version.package, app.package_name, app_version.version_name, app.name))
示例4: float_arg
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def float_arg(request: Request,
key: Text,
default: Optional[float] = None) -> Optional[float]:
"""Return a passed argument cast as a float or None.
Checks the `name` parameter of the request if it contains a valid
float value. If not, `None` is returned."""
arg = default_arg(request, key, default)
if arg is default:
return arg
try:
return float(arg)
except (ValueError, TypeError):
logger.warning("Failed to convert '{}' to float.".format(arg))
return default
示例5: event_verbosity_parameter
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def event_verbosity_parameter(
request: Request, default_verbosity: EventVerbosity
) -> EventVerbosity:
"""Create `EventVerbosity` object using request params if present."""
event_verbosity_str = request.args.get(
"include_events", default_verbosity.name
).upper()
try:
return EventVerbosity[event_verbosity_str]
except KeyError:
enum_values = ", ".join([e.name for e in EventVerbosity])
raise ErrorResponse(
400,
"BadRequest",
"Invalid parameter value for 'include_events'. "
"Should be one of {}".format(enum_values),
{"parameter": "include_events", "in": "query"},
)
示例6: float_arg
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def float_arg(
request: Request, key: Text, default: Optional[float] = None
) -> Optional[float]:
"""Return a passed argument cast as a float or None.
Checks the `name` parameter of the request if it contains a valid
float value. If not, `None` is returned."""
arg = request.args.get(key, default)
if arg is default:
return arg
try:
return float(str(arg))
except (ValueError, TypeError):
logger.warning(f"Failed to convert '{arg}' to float.")
return default
示例7: _extract_message
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def _extract_message(self, req: Request) -> Text:
if req.json["type"] == "MESSAGE":
message = req.json["message"]["text"]
elif req.json["type"] == "CARD_CLICKED":
message = req.json["action"]["actionMethodName"]
elif req.json["type"] == "ADDED_TO_SPACE":
if self._extract_room(req) and self.hangouts_room_added_intent_name:
message = self.hangouts_room_added_intent_name
elif not self._extract_room(req) and self.hangouts_user_added_intent_name:
message = self.hangouts_user_added_intent_name
elif (
req.json["type"] == "REMOVED_FROM_SPACE"
and self.hangouts_user_added_intent_name
):
message = self.hangouts_user_added_intent_name
else:
message = ""
return message
示例8: get_metadata
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def get_metadata(self, request: Request) -> Dict[Text, Any]:
"""Extracts the metadata from a slack API event (https://api.slack.com/types/event).
Args:
request: A `Request` object that contains a slack API event in the body.
Returns:
Metadata extracted from the sent event payload. This includes the output channel for the response,
and users that have installed the bot.
"""
slack_event = request.json
event = slack_event.get("event", {})
return {
"out_channel": event.get("channel"),
"users": slack_event.get("authed_users"),
}
示例9: model_server_app
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def model_server_app(model_path: Text, model_hash: Text = "somehash") -> Sanic:
app = Sanic(__name__)
app.number_of_model_requests = 0
@app.route("/model", methods=["GET"])
async def model(request: Request) -> StreamingHTTPResponse:
"""Simple HTTP model server responding with a trained model."""
if model_hash == request.headers.get("If-None-Match"):
return response.text("", 204)
app.number_of_model_requests += 1
return await response.file_stream(
location=model_path,
headers={"ETag": model_hash, "filename": model_path},
mime_type="application/gzip",
)
return app
示例10: on_request
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def on_request(request: Request) -> None:
"""Middleware function that runs prior to processing a request via Sanic."""
# Generate a unique request ID and use it as a field in any logging that
# takes place during the request handling.
req_id = shortuuid.uuid()
request.ctx.uuid = req_id
contextvars.clear_contextvars()
contextvars.bind_contextvars(
request_id=req_id,
)
logger.debug(
'processing HTTP request',
method=request.method,
ip=request.ip,
path=request.path,
headers=dict(request.headers),
args=request.args,
)
示例11: on_response
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def on_response(request: Request, response: HTTPResponse) -> None:
"""Middleware function that runs prior to returning a response via Sanic."""
# Default bytes. If this is a StreamingHTTPResponse, this value is
# used, since there is no response.body for those responses.
# (https://github.com/vapor-ware/synse-server/issues/396)
byte_count = -1
if hasattr(response, 'body') and response.body is not None:
byte_count = len(response.body)
logger.debug(
'returning HTTP response',
request=f'{request.method} {request.url}',
status=response.status,
bytes=byte_count,
)
# Unbind the request ID from the logger.
contextvars.unbind_contextvars(
'request_id',
)
示例12: version
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def version(request: Request) -> HTTPResponse:
"""Get the version information for the Synse Server instance.
The API version provided by this endpoint should be used in subsequent
versioned requests to the instance.
Args:
request: The Sanic request object.
Returns:
A JSON-formatted HTTP response with the possible statuses:
* 200: OK
* 500: Catchall processing error
"""
try:
return utils.http_json_response(
await cmd.version(),
)
except Exception:
logger.exception('failed to get version info')
raise
示例13: config
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def config(request: Request) -> HTTPResponse:
"""Get the unified configuration for the Synse Server instance.
This endpoint is provided as a convenient way to determine the settings
that the Synse Server instance is running with. Synse Server can be configured
with default values, values from file, and values from the environment. This
endpoint provides the final joined configuration of all config sources.
Args:
request: The Sanic request object.
Returns:
A JSON-formatted HTTP response with the possible statuses:
* 200: OK
* 500: Catchall processing error
"""
try:
return utils.http_json_response(
await cmd.config(),
)
except Exception:
logger.exception('failed to get server config')
raise
示例14: plugins
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def plugins(request: Request) -> HTTPResponse:
"""Get a summary of all the plugins currently registered with Synse Server.
Args:
request: The Sanic request object.
Returns:
A JSON-formatted HTTP response with the possible statuses:
* 200: OK
* 500: Catchall processing error
"""
refresh = request.args.get('refresh', 'false').lower() == 'true'
try:
return utils.http_json_response(
await cmd.plugins(
refresh=refresh,
),
)
except Exception:
logger.exception('failed to get plugins')
raise
示例15: plugin_info
# 需要導入模塊: from sanic import request [as 別名]
# 或者: from sanic.request import Request [as 別名]
def plugin_info(request: Request, plugin_id: str) -> HTTPResponse:
"""Get detailed information on the specified plugin.
Args:
request: The Sanic request object.
plugin_id: The ID of the plugin to get information for.
Returns:
A JSON-formatted HTTP response with the possible statuses:
* 200: OK
* 404: Plugin not found
* 500: Catchall processing error
"""
try:
return utils.http_json_response(
await cmd.plugin(plugin_id),
)
except Exception:
logger.exception('failed to get plugin info', id=plugin_id)
raise