Python starlette.responses.Response() Examples

The following are 30 code examples of starlette.responses.Response(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module starlette.responses , or try the search function .
Example #1
Source File: _endpoints.py    From tartiflette-asgi with MIT License 7 votes vote down vote up
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) 
Example #2
Source File: web.py    From mergify-engine with Apache License 2.0 6 votes vote down vote up
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) 
Example #3
Source File: applications.py    From fastapi with MIT License 6 votes vote down vote up
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,
        ) 
Example #4
Source File: middleware.py    From starlette-prometheus with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: endpoints.py    From polyaxon with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: app.py    From mquery with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: utils.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #8
Source File: _endpoints.py    From tartiflette-asgi with MIT License 6 votes vote down vote up
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) 
Example #9
Source File: starlette.py    From keycloak-client with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #10
Source File: utils.py    From fastapi with MIT License 6 votes vote down vote up
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 
Example #11
Source File: asgi.py    From ariadne with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #12
Source File: routes.py    From fastapi_contrib with MIT License 6 votes vote down vote up
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 
Example #13
Source File: middlewares.py    From fastapi_contrib with MIT License 6 votes vote down vote up
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 
Example #14
Source File: __init__.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
        """Processes the whole request APM capturing.

        Args:
            request (Request)
            call_next (RequestResponseEndpoint): Next request process in Starlette.

        Returns:
            Response
        """
        await self._request_started(request)

        try:
            response = await call_next(request)
        except Exception:
            await self.capture_exception(
                context={"request": await get_data_from_request(request, self.client.config, constants.ERROR)}
            )
            elasticapm.set_transaction_result("HTTP 5xx", override=False)
            elasticapm.set_context({"status_code": 500}, "response")

            raise
        else:
            await self._request_finished(response)
        finally:
            self.client.end_transaction()

        return response 
Example #15
Source File: endpoints.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def health(request):
    return Response(status_code=status.HTTP_200_OK) 
Example #16
Source File: _endpoints.py    From tartiflette-asgi with MIT License 5 votes vote down vote up
def get(self, request: Request) -> Response:
        return await self._get_response(request, data=request.query_params) 
Example #17
Source File: endpoints.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def collect_logs(request):
    owner = request.path_params["owner"]
    project = request.path_params["project"]
    run_uuid = request.path_params["run_uuid"]
    resource_name = get_resource_name(run_uuid=run_uuid)
    operation = get_run_instance(owner=owner, project=project, run_uuid=run_uuid)
    k8s_manager = AsyncK8SManager(
        namespace=settings.CLIENT_CONFIG.namespace,
        in_cluster=settings.CLIENT_CONFIG.in_cluster,
    )
    await k8s_manager.setup()
    k8s_operation = await get_k8s_operation(
        k8s_manager=k8s_manager, resource_name=resource_name
    )
    if not k8s_operation:
        raise HTTPException(
            detail="Run's logs was not collected, resource was not found.",
            status_code=status.HTTP_400_BAD_REQUEST,
        )
    operation_logs, _ = await get_k8s_operation_logs(
        operation=operation, k8s_manager=k8s_manager, last_time=None
    )
    if k8s_manager:
        await k8s_manager.close()
    if not operation_logs:
        return Response()

    logs = operation_logs
    task = BackgroundTask(upload_logs, run_uuid=run_uuid, logs=logs)
    return Response(background=task) 
Example #18
Source File: test_context.py    From tartiflette-asgi with MIT License 5 votes vote down vote up
def test_access_request_from_graphql_context(
    engine: Engine, authorization: str, expected_user: str,
) -> None:
    class FakeAuthMiddleware(BaseHTTPMiddleware):
        async def dispatch(
            self, request: Request, call_next: typing.Callable
        ) -> Response:
            request.state.user = (
                "Jane" if request.headers["authorization"] == "Bearer 123" else None
            )
            return await call_next(request)

    graphql = TartifletteApp(engine=engine)
    app = Starlette(
        routes=[Mount("/", graphql)],
        middleware=[Middleware(FakeAuthMiddleware)],
        on_startup=[graphql.startup],
    )

    async with get_client(app) as client:
        # See `tests/resolvers.py` for the `whoami` resolver.
        response = await client.post(
            "/", json={"query": "{ whoami }"}, headers={"Authorization": authorization},
        )

    assert response.status_code == 200
    assert response.json() == {"data": {"whoami": expected_user}} 
Example #19
Source File: utils.py    From aioli with MIT License 5 votes vote down vote up
def jsonify(content, status=200, **kwargs):
    return Response(
        content=ujson.dumps(content, ensure_ascii=False, **kwargs).encode("utf8"),
        status_code=status,
        headers={"content-type": "application/json"},
    ) 
Example #20
Source File: view.py    From pygraphy with MIT License 5 votes vote down vote up
def post(self, request):
        content_type = request.headers.get("Content-Type", "")

        if "application/json" in content_type:
            data = await request.json()
        elif "application/graphql" in content_type:
            body = await request.body()
            text = body.decode()
            data = {"query": text}
        elif "query" in request.query_params:
            data = request.query_params
        else:
            return PlainTextResponse(
                "Unsupported Media Type",
                status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
            )

        try:
            query = data["query"]
            variables = data.get("variables")
        except KeyError:
            return PlainTextResponse(
                "No GraphQL query found in the request",
                status_code=status.HTTP_400_BAD_REQUEST,
            )

        result = await self.execute(
            query, variables=variables, request=request
        )
        status_code = status.HTTP_200_OK
        return Response(
            json.dumps(result, cls=GraphQLEncoder),
            status_code=status_code,
            media_type='application/json'
        ) 
Example #21
Source File: _endpoints.py    From tartiflette-asgi with MIT License 5 votes vote down vote up
def get(self, request: Request) -> Response:
        config = get_graphql_config(request)
        graphql_endpoint = request["root_path"] + config.path
        subscriptions_endpoint = None
        if config.subscriptions:
            subscriptions_endpoint = request["root_path"] + config.subscriptions.path
        graphiql = config.graphiql
        assert graphiql is not None
        html = graphiql.render_template(
            graphql_endpoint=graphql_endpoint,
            subscriptions_endpoint=subscriptions_endpoint,
        )
        return HTMLResponse(html) 
Example #22
Source File: web.py    From mergify-engine with Apache License 2.0 5 votes vote down vote up
def marketplace_testng_handler(request: requests.Request):  # pragma: no cover
    event_type = request.headers.get("X-GitHub-Event")
    event_id = request.headers.get("X-GitHub-Delivery")
    data = await request.json()
    LOG.debug(
        "received marketplace testing events",
        event_type=event_type,
        event_id=event_id,
        data=data,
    )
    return responses.Response("Event ignored", status_code=202) 
Example #23
Source File: endpoints.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def notify(request):
    namespace = request.path_params["namespace"]
    owner = request.path_params["owner"]
    project = request.path_params["project"]
    run_uuid = request.path_params["run_uuid"]
    body = await request.json()
    run_name = body.get("name")
    condition = body.get("condition")
    if not condition:
        raise HTTPException(
            detail="Received a notification request without condition.",
            status_code=status.HTTP_400_BAD_REQUEST,
        )
    condition = V1StatusCondition.get_condition(**condition)
    connections = body.get("connections")
    if not connections:
        raise HTTPException(
            detail="Received a notification request without connections.",
            status_code=status.HTTP_400_BAD_REQUEST,
        )

    if not settings.AGENT_CONFIG.notification_connections:
        raise HTTPException(
            detail="Run's logs was not collected, resource was not found.",
            status_code=status.HTTP_400_BAD_REQUEST,
        )

    task = BackgroundTask(
        notify_run,
        namespace=namespace,
        owner=owner,
        project=project,
        run_uuid=run_uuid,
        run_name=run_name,
        condition=condition,
        connections=connections,
    )
    return Response(background=task) 
Example #24
Source File: web.py    From mergify-engine with Apache License 2.0 5 votes vote down vote up
def event_testing_handler_post(request: requests.Request):  # pragma: no cover
    r = await utils.get_aredis_for_cache()
    event_type = request.headers.get("X-GitHub-Event")
    event_id = request.headers.get("X-GitHub-Delivery")
    data = await request.json()
    await r.rpush(
        "events-testing",
        json.dumps({"id": event_id, "type": event_type, "payload": data}),
    )
    return responses.Response("Event queued", status_code=202) 
Example #25
Source File: web.py    From mergify-engine with Apache License 2.0 5 votes vote down vote up
def event_handler(request: requests.Request,):
    event_type = request.headers.get("X-GitHub-Event")
    event_id = request.headers.get("X-GitHub-Delivery")
    data = await request.json()

    try:
        await github_events.job_filter_and_dispatch(
            app.aredis_stream, event_type, event_id, data
        )
    except github_events.IgnoredEvent as ie:
        status_code = 200
        reason = f"Event ignored: {ie.reason}"
    else:
        status_code = 202
        reason = "Event queued"

    if (
        config.WEBHOOK_APP_FORWARD_URL
        and config.WEBHOOK_FORWARD_EVENT_TYPES is not None
        and event_type in config.WEBHOOK_FORWARD_EVENT_TYPES
    ):
        raw = await request.body()
        await http_post(
            config.WEBHOOK_APP_FORWARD_URL,
            data=raw.decode(),
            headers={
                "X-GitHub-Event": event_type,
                "X-GitHub-Delivery": event_id,
                "X-Hub-Signature": request.headers.get("X-Hub-Signature"),
                "User-Agent": request.headers.get("User-Agent"),
                "Content-Type": request.headers.get("Content-Type"),
            },
        )

    return responses.Response(reason, status_code=status_code)


# NOTE(sileht): These endpoints are used for recording cassetes, we receive
# Github event on POST, we store them is redis, GET to retreive and delete 
Example #26
Source File: web.py    From mergify-engine with Apache License 2.0 5 votes vote down vote up
def marketplace_handler(request: requests.Request,):  # pragma: no cover
    event_type = request.headers.get("X-GitHub-Event")
    event_id = request.headers.get("X-GitHub-Delivery")
    data = await request.json()

    LOG.info(
        "Marketplace event",
        event_type=event_type,
        event_id=event_id,
        sender=data["sender"]["login"],
        gh_owner=data["marketplace_purchase"]["account"]["login"],
    )

    await cleanup_subscription(data)

    if config.WEBHOOK_MARKETPLACE_FORWARD_URL:
        raw = await request.body()
        await http_post(
            config.WEBHOOK_MARKETPLACE_FORWARD_URL,
            data=raw.decode(),
            headers={
                "X-GitHub-Event": event_type,
                "X-GitHub-Delivery": event_id,
                "X-Hub-Signature": request.headers.get("X-Hub-Signature"),
                "User-Agent": request.headers.get("User-Agent"),
                "Content-Type": request.headers.get("Content-Type"),
            },
        )

    return responses.Response("Event queued", status_code=202) 
Example #27
Source File: web.py    From mergify-engine with Apache License 2.0 5 votes vote down vote up
def subscription_cache_delete(installation_id):  # pragma: no cover
    r = await utils.get_aredis_for_cache()
    await r.delete("subscription-cache-%s" % installation_id)
    return responses.Response("Cache cleaned", status_code=200) 
Example #28
Source File: web.py    From mergify-engine with Apache License 2.0 5 votes vote down vote up
def subscription_cache_update(
    installation_id, request: requests.Request
):  # pragma: no cover
    sub = await request.json()
    if sub is None:
        return responses.Response("Empty content", status_code=400)
    await sub_utils.save_subscription_to_cache(installation_id, sub)
    return responses.Response("Cache updated", status_code=200) 
Example #29
Source File: endpoints.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def not_found(request, exc):
    """
    Return an HTTP 404 page.
    """
    return Response(status_code=status.HTTP_404_NOT_FOUND) 
Example #30
Source File: starlette.py    From keycloak-client with GNU General Public License v3.0 5 votes vote down vote up
def get(self, request: Request) -> Response:
        # tokens = json.loads(request.session["tokens"])
        # access_token = tokens["access_token"]
        # refresh_token = tokens["refresh_token"]
        # self.kc.logout(access_token, refresh_token)
        del request.session["user"]
        return Response("User logged out successfully", status_code=204)