Python starlette.requests.Request() Examples

The following are 30 code examples of starlette.requests.Request(). 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.requests , or try the search function .
Example #1
Source File: pagination.py    From fastapi_contrib with MIT License 8 votes vote down vote up
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 
Example #2
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 #3
Source File: test_pagination.py    From fastapi_contrib with MIT License 7 votes vote down vote up
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}],
    } 
Example #4
Source File: fastapi_login.py    From fastapi_login with MIT License 7 votes vote down vote up
def __call__(self, request: Request):
        """
        Provides the functionality to act as a Dependency

        :param Request request: The incoming request, this is set automatically
            by FastAPI
        :return: The user object or None
        :raises: The not_authenticated_exception if set by the user
        """

        if self.not_authenticated_exception is None:
            self.oauth_scheme = OAuth2PasswordBearer(tokenUrl=self.tokenUrl)
        else:
            # we handle Exception raising
            self.oauth_scheme = OAuth2PasswordBearer(tokenUrl=self.tokenUrl, auto_error=False)

        token = await self.oauth_scheme(request)
        if token is not None:
            return await self.get_current_user(token)

        # No token is present in the request and no Exception has been raised yet
        raise self.not_authenticated_exception 
Example #5
Source File: middlewares.py    From fastapi_contrib with MIT License 6 votes vote down vote up
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 
Example #6
Source File: start.py    From BMW-TensorFlow-Training-GUI with Apache License 2.0 6 votes vote down vote up
def detect_robotron(request: Request, background_tasks: BackgroundTasks, model: str = Form(...), image: UploadFile = File(...)):
	"""
	Performs a prediction for a specified image using one of the available models.
	:param request: Used if background tasks was enabled
	:param background_tasks: Used if background tasks was enabled
	:param model: Model name or model hash
	:param image: Image file
	:return: Model's Bounding boxes
	"""
	draw_boxes = False
	predict_batch = False
	try:
		request_start = time.time()
		output = await dl_service.run_model(model, image, draw_boxes, predict_batch)
		# background_tasks.add_task(metrics_collector,'detect',image, output, request, request_start)
		error_logging.info('request successful;' + str(output))
		return output
	except ApplicationError as e:
		error_logging.warning(model+';'+str(e))
		return ApiResponse(success=False, error=e)
	except Exception as e:
		error_logging.error(model+' '+str(e))
		return ApiResponse(success=False, error='unexpected server error') 
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_body(request: Request) -> str:
    """Gets body from the request.

    todo: This is not very pretty however it is not usual to get request body out of the target method (business logic).

    Args:
        request (Request)

    Returns:
        str
    """
    body = await request.body()
    await set_body(request, body)

    request._stream_consumed = False

    return body.decode("utf-8") 
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: 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 #10
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 #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: web.py    From mergify-engine with Apache License 2.0 6 votes vote down vote up
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}
    ) 
Example #13
Source File: debugtalk.py    From httprunner with Apache License 2.0 6 votes vote down vote up
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 
Example #14
Source File: web.py    From mergify-engine with Apache License 2.0 6 votes vote down vote up
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) 
Example #15
Source File: test_permissions.py    From fastapi_contrib with MIT License 6 votes vote down vote up
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." 
Example #16
Source File: test_pagination.py    From fastapi_contrib with MIT License 6 votes vote down vote up
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}],
    } 
Example #17
Source File: web.py    From mergify-engine with Apache License 2.0 6 votes vote down vote up
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) 
Example #18
Source File: test_pagination.py    From fastapi_contrib with MIT License 6 votes vote down vote up
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}],
    } 
Example #19
Source File: test_pagination.py    From fastapi_contrib with MIT License 6 votes vote down vote up
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}],
    } 
Example #20
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 #21
Source File: exception_handlers.py    From fastapi_contrib with MIT License 6 votes vote down vote up
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) 
Example #22
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 #23
Source File: main.py    From LuWu with Apache License 2.0 5 votes vote down vote up
def validation_exception_handler(request: Request, exc: RequestValidationError):
    failed_res = BaseFailedResponseModel(errors=exc.errors()).dict()
    return JSONResponse(failed_res, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY) 
Example #24
Source File: middlewares.py    From fastapi_contrib with MIT License 5 votes vote down vote up
def request_id_header_name(self) -> str:
        """
        Gets the name of Request ID header from the project settings.
        :return: string with Request ID header name
        """
        return settings.request_id_header 
Example #25
Source File: _endpoints.py    From tartiflette-asgi with MIT License 5 votes vote down vote up
def dispatch(self) -> None:
        request = Request(self.scope, self.receive)
        graphiql = get_graphql_config(request).graphiql
        if "text/html" in request.headers.get("Accept", ""):
            app: ASGIApp
            if graphiql and graphiql.path is None:
                app = GraphiQLEndpoint
            else:
                app = PlainTextResponse("Not Found", 404)
            await app(self.scope, self.receive, self.send)
        else:
            await super().dispatch() 
Example #26
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 #27
Source File: main.py    From LuWu with Apache License 2.0 5 votes vote down vote up
def catch_exceptions_middleware(request: Request, call_next):
    try:
        return await call_next(request)
    except Exception as e:
        logging.warning(traceback.format_exc())
        exc_data = {
            'msg': "Internal server error",
            'detail': str(e)
        }
        failed_res = BaseFailedResponseModel(errors=[exc_data]).dict()
        return JSONResponse(failed_res, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) 
Example #28
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 #29
Source File: utils.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_body(request: Request, body: bytes):
    """Overwrites body in Starlette.

    Args:
        request (Request)
        body (bytes)
    """

    async def receive() -> Message:
        return {"type": "http.request", "body": body}

    request._receive = receive 
Example #30
Source File: main.py    From LuWu with Apache License 2.0 5 votes vote down vote up
def http_exception_handler(request: Request, exc: HTTPException):
    failed_res = BaseFailedResponseModel(errors=[exc.detail]).dict()
    status_code = exc.status_code or status.HTTP_400_BAD_REQUEST
    return JSONResponse(failed_res, status_code=status_code)