当前位置: 首页>>代码示例>>Python>>正文


Python request.Request方法代码示例

本文整理汇总了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")) 
开发者ID:huge-success,项目名称:sanic,代码行数:19,代码来源:server.py

示例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)) 
开发者ID:huge-success,项目名称:sanic,代码行数:26,代码来源:server.py

示例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)) 
开发者ID:skytoup,项目名称:AppServer,代码行数:24,代码来源:app_versions.py

示例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 
开发者ID:RasaHQ,项目名称:rasa_core,代码行数:20,代码来源:utils.py

示例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"},
        ) 
开发者ID:botfront,项目名称:rasa-for-botfront,代码行数:20,代码来源:server.py

示例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 
开发者ID:botfront,项目名称:rasa-for-botfront,代码行数:20,代码来源:endpoints.py

示例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 
开发者ID:botfront,项目名称:rasa-for-botfront,代码行数:25,代码来源:hangouts.py

示例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"),
        } 
开发者ID:botfront,项目名称:rasa-for-botfront,代码行数:19,代码来源:slack.py

示例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 
开发者ID:botfront,项目名称:rasa-for-botfront,代码行数:22,代码来源:test_agent.py

示例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,
    ) 
开发者ID:vapor-ware,项目名称:synse-server,代码行数:22,代码来源:app.py

示例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',
    ) 
开发者ID:vapor-ware,项目名称:synse-server,代码行数:23,代码来源:app.py

示例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 
开发者ID:vapor-ware,项目名称:synse-server,代码行数:23,代码来源:http.py

示例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 
开发者ID:vapor-ware,项目名称:synse-server,代码行数:25,代码来源:http.py

示例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 
开发者ID:vapor-ware,项目名称:synse-server,代码行数:24,代码来源:http.py

示例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 
开发者ID:vapor-ware,项目名称:synse-server,代码行数:22,代码来源:http.py


注:本文中的sanic.request.Request方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。