當前位置: 首頁>>代碼示例>>Python>>正文


Python responses.Response方法代碼示例

本文整理匯總了Python中starlette.responses.Response方法的典型用法代碼示例。如果您正苦於以下問題:Python responses.Response方法的具體用法?Python responses.Response怎麽用?Python responses.Response使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在starlette.responses的用法示例。


在下文中一共展示了responses.Response方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: dispatch

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [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 
開發者ID:perdy,項目名稱:starlette-prometheus,代碼行數:27,代碼來源:middleware.py

示例2: include_router

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [as 別名]
def include_router(
        self,
        router: routing.APIRouter,
        *,
        prefix: str = "",
        tags: List[str] = None,
        dependencies: Sequence[Depends] = None,
        responses: Dict[Union[int, str], Dict[str, Any]] = None,
        default_response_class: Optional[Type[Response]] = None,
    ) -> None:
        self.router.include_router(
            router,
            prefix=prefix,
            tags=tags,
            dependencies=dependencies,
            responses=responses or {},
            default_response_class=default_response_class
            or self.default_response_class,
        ) 
開發者ID:tiangolo,項目名稱:fastapi,代碼行數:21,代碼來源:applications.py

示例3: add_non_field_param_to_dependency

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [as 別名]
def add_non_field_param_to_dependency(
    *, param: inspect.Parameter, dependant: Dependant
) -> Optional[bool]:
    if lenient_issubclass(param.annotation, Request):
        dependant.request_param_name = param.name
        return True
    elif lenient_issubclass(param.annotation, WebSocket):
        dependant.websocket_param_name = param.name
        return True
    elif lenient_issubclass(param.annotation, Response):
        dependant.response_param_name = param.name
        return True
    elif lenient_issubclass(param.annotation, BackgroundTasks):
        dependant.background_tasks_param_name = param.name
        return True
    elif lenient_issubclass(param.annotation, SecurityScopes):
        dependant.security_scopes_param_name = param.name
        return True
    return None 
開發者ID:tiangolo,項目名稱:fastapi,代碼行數:21,代碼來源:utils.py

示例4: graphql_http_server

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [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) 
開發者ID:mirumee,項目名稱:ariadne,代碼行數:27,代碼來源:asgi.py

示例5: get_route_handler

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [as 別名]
def get_route_handler(self) -> Callable:
        original_route_handler = super().get_route_handler()

        async def custom_route_handler(request: Request) -> Response:
            try:
                return await original_route_handler(request)
            except RequestValidationError as exc:
                body = await request.body()
                if not body:
                    status_code = 400
                    data = {
                        "code": status_code,
                        "detail": "Empty body for this request is not valid.",
                        "fields": [],
                    }
                    return UJSONResponse(data, status_code=status_code)
                else:
                    raise exc

        return custom_route_handler 
開發者ID:identixone,項目名稱:fastapi_contrib,代碼行數:22,代碼來源:routes.py

示例6: dispatch

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [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 
開發者ID:identixone,項目名稱:fastapi_contrib,代碼行數:22,代碼來源:middlewares.py

示例7: _refresh

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [as 別名]
def _refresh(owner, repo, action="user", **extra_data):
    event_type = "refresh"
    data = {
        "action": action,
        "repository": {
            "name": repo,
            "owner": {"login": owner},
            "full_name": f"{owner}/{repo}",
        },
        "sender": {"login": "<internal>"},
    }
    data.update(extra_data)

    await github_events.job_filter_and_dispatch(
        app.aredis_stream, event_type, str(uuid.uuid4()), data
    )

    return responses.Response("Refresh queued", status_code=202) 
開發者ID:Mergifyio,項目名稱:mergify-engine,代碼行數:20,代碼來源:web.py

示例8: get

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [as 別名]
def get(self, request: Request) -> Response:

        # validate state
        state = request.query_params["state"]
        _state = request.session.pop("state", "unknown")
        if state != _state:
            return PlainTextResponse("Invalid state", status_code=403)

        # retrieve tokens
        code = request.query_params["code"]
        tokens = self.kc.callback(code)
        # request.session["tokens"] = json.dumps(tokens)

        # retrieve user info
        access_token = tokens["access_token"]
        user = self.kc.fetch_userinfo(access_token)
        request.session["user"] = json.dumps(user)

        return RedirectResponse(self.redirect_uri) 
開發者ID:chunky-monkeys,項目名稱:keycloak-client,代碼行數:21,代碼來源:starlette.py

示例9: get_data_from_response

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [as 別名]
def get_data_from_response(response: Response, config: Config, event_type: str) -> dict:
    """Loads data from response for APM capturing.

    Args:
        response (Response)
        config (Config)
        event_type (str)

    Returns:
        dict
    """
    result = {}

    if isinstance(getattr(response, "status_code", None), compat.integer_types):
        result["status_code"] = response.status_code

    if config.capture_headers and getattr(response, "headers", None):
        headers = response.headers
        result["headers"] = {key: ";".join(headers.getlist(key)) for key in compat.iterkeys(headers)}

    if config.capture_body in ("all", event_type) and hasattr(response, "body"):
        result["body"] = response.body.decode("utf-8")

    return result 
開發者ID:elastic,項目名稱:apm-agent-python,代碼行數:26,代碼來源:utils.py

示例10: post

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [as 別名]
def post(self, request: Request) -> Response:
        content_type = request.headers.get("Content-Type", "")

        if "application/json" in content_type:
            try:
                data = await request.json()
            except json.JSONDecodeError:
                return JSONResponse({"error": "Invalid JSON."}, 400)
        elif "application/graphql" in content_type:
            body = await request.body()
            data = {"query": body.decode()}
        elif "query" in request.query_params:
            data = request.query_params
        else:
            return PlainTextResponse("Unsupported Media Type", 415)

        return await self._get_response(request, data=data) 
開發者ID:tartiflette,項目名稱:tartiflette-asgi,代碼行數:19,代碼來源:_endpoints.py

示例11: _get_response

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [as 別名]
def _get_response(self, request: Request, data: QueryParams) -> Response:
        try:
            query = data["query"]
        except KeyError:
            return PlainTextResponse("No GraphQL query found in the request", 400)

        config = get_graphql_config(request)
        background = BackgroundTasks()
        context = {"req": request, "background": background, **config.context}

        engine: Engine = config.engine
        result: dict = await engine.execute(
            query,
            context=context,
            variables=data.get("variables"),
            operation_name=data.get("operationName"),
        )

        content = {"data": result["data"]}
        has_errors = "errors" in result
        if has_errors:
            content["errors"] = format_errors(result["errors"])
        status = 400 if has_errors else 200

        return JSONResponse(content=content, status_code=status, background=background) 
開發者ID:tartiflette,項目名稱:tartiflette-asgi,代碼行數:27,代碼來源:_endpoints.py

示例12: download_artifact

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [as 別名]
def download_artifact(request):
    run_uuid = request.path_params["run_uuid"]
    filepath = request.query_params.get("path", "")
    stream = to_bool(request.query_params.get("stream"), handle_none=True)
    force = to_bool(request.query_params.get("force"), handle_none=True)
    if not filepath:
        return Response(
            content="A `path` query param is required to stream a file content",
            status_code=status.HTTP_400_BAD_REQUEST,
        )
    subpath = "{}/{}".format(run_uuid, filepath).rstrip("/")
    archived_path = await download_file(subpath=subpath, check_cache=not force)
    if not archived_path:
        return Response(
            content="Artifact not found: filepath={}".format(archived_path),
            status_code=status.HTTP_404_NOT_FOUND,
        )
    if stream:
        return FileResponse(archived_path)
    return redirect(archived_path) 
開發者ID:polyaxon,項目名稱:polyaxon,代碼行數:22,代碼來源:endpoints.py

示例13: add_headers

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [as 別名]
def add_headers(request: Request, call_next: Callable) -> Response:
    response = await call_next(request)
    response.headers["X-Frame-Options"] = "deny"
    response.headers["Access-Control-Allow-Origin"] = request.client.host
    response.headers[
        "Access-Control-Allow-Headers"
    ] = "cache-control,x-requested-with,content-type,authorization"
    response.headers[
        "Access-Control-Allow-Methods"
    ] = "POST, PUT, GET, OPTIONS, DELETE"
    return response 
開發者ID:CERT-Polska,項目名稱:mquery,代碼行數:13,代碼來源:app.py

示例14: download_hashes

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [as 別名]
def download_hashes(hash: str) -> Response:
    hashes = "\n".join(
        d["meta"]["sha256"]["display_text"]
        for d in db.get_job_matches(JobId(hash)).matches
    )
    return Response(hashes + "\n") 
開發者ID:CERT-Polska,項目名稱:mquery,代碼行數:8,代碼來源:app.py

示例15: metrics

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import Response [as 別名]
def metrics(request: Request) -> Response:
    if "prometheus_multiproc_dir" in os.environ:
        registry = CollectorRegistry()
        MultiProcessCollector(registry)
    else:
        registry = REGISTRY

    return Response(generate_latest(registry), media_type=CONTENT_TYPE_LATEST) 
開發者ID:perdy,項目名稱:starlette-prometheus,代碼行數:10,代碼來源:view.py


注:本文中的starlette.responses.Response方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。