Python starlette.responses.PlainTextResponse() Examples

The following are 30 code examples of starlette.responses.PlainTextResponse(). 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: test_end_to_end.py    From starlette-prometheus with GNU General Public License v3.0 6 votes vote down vote up
def app(self):
        app_ = Starlette()
        app_.add_middleware(PrometheusMiddleware)
        app_.add_route("/metrics/", metrics)

        @app_.route("/foo/")
        def foo(request):
            return PlainTextResponse("Foo")

        @app_.route("/bar/")
        def bar(request):
            raise ValueError("bar")

        @app_.route("/foo/{bar}/")
        def foobar(request):
            return PlainTextResponse(f"Foo: {request.path_params['bar']}")

        return app_ 
Example #3
Source File: test_mount.py    From tartiflette-asgi with MIT License 6 votes vote down vote up
def test_tartiflette_app_as_sub_starlette_app(engine: Engine) -> None:
    async def home(_request: Request) -> PlainTextResponse:
        return PlainTextResponse("Hello, world!")

    graphql = TartifletteApp(engine=engine)
    routes = [
        Route("/", endpoint=home),
        Mount("/graphql", app=graphql, name="tartiflette-asgi"),
    ]
    app = Starlette(routes=routes, on_startup=[graphql.startup])

    async with get_client(app) as client:
        response = await client.get("/")
        assert response.status_code == 200
        assert response.text == "Hello, world!"
        response = await client.get("/graphql?query={ hello }")
        assert response.status_code == 200
        assert response.json() == {"data": {"hello": "Hello stranger"}} 
Example #4
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 #5
Source File: starlette_tests.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def app(elasticapm_client):
    app = Starlette()

    @app.route("/", methods=["GET", "POST"])
    async def hi(request):
        with async_capture_span("test"):
            pass
        return PlainTextResponse("ok")

    @app.route("/raise-exception", methods=["GET", "POST"])
    async def raise_exception(request):
        raise ValueError()

    app.add_middleware(ElasticAPM, client=elasticapm_client)

    return app 
Example #6
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 #7
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 #8
Source File: test_asgi.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def app():
    app = Starlette()

    @app.route("/sync-message")
    def hi(request):
        capture_message("hi", level="error")
        return PlainTextResponse("ok")

    @app.route("/async-message")
    async def hi2(request):
        capture_message("hi", level="error")
        return PlainTextResponse("ok")

    app.add_middleware(SentryAsgiMiddleware)

    return app 
Example #9
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 #10
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def metrics(request: Request):
    content, http_headers = render(
        app.registry, [request.headers.get("accept", "application/json")])
    return PlainTextResponse(content, headers=http_headers) 
Example #11
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def health(request: Request) -> PlainTextResponse:
    return PlainTextResponse(content=b"") 
Example #12
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def health(request: Request) -> PlainTextResponse:
    return PlainTextResponse(content=b"") 
Example #13
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def metrics(request: Request):
    content, http_headers = render(
        app.registry, [request.headers.get("accept", "application/json")])
    return PlainTextResponse(content, headers=http_headers) 
Example #14
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def health(request: Request) -> PlainTextResponse:
    return PlainTextResponse(content=b"") 
Example #15
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def metrics(request: Request):
    content, http_headers = render(
        app.registry, [request.headers.get("accept", "application/json")])
    return PlainTextResponse(content, headers=http_headers) 
Example #16
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def health(request: Request) -> PlainTextResponse:
    return PlainTextResponse(content=b"", status_code=500) 
Example #17
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def health(request: Request) -> PlainTextResponse:
    return PlainTextResponse(content=b"") 
Example #18
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def metrics(request: Request):
    content, http_headers = render(
        app.registry, [request.headers.get("accept", "application/json")])
    return PlainTextResponse(content, headers=http_headers) 
Example #19
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def health(request: Request) -> PlainTextResponse:
    return PlainTextResponse(content=b"") 
Example #20
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def metrics(request: Request):
    content, http_headers = render(
        app.registry, [request.headers.get("accept", "application/json")])
    return PlainTextResponse(content, headers=http_headers) 
Example #21
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def health(request: Request) -> PlainTextResponse:
    return PlainTextResponse(content=b"") 
Example #22
Source File: test_middleware_asgi.py    From bocadillo with MIT License 5 votes vote down vote up
def test_send_response_in_middleware(app: App, client):
    class Middleware(ASGIMiddleware):
        async def __call__(self, scope, receive, send):
            response = PlainTextResponse("OK")
            await response(scope, receive, send)

    app.add_middleware(Middleware)

    r = client.get("/")
    assert r.status_code == 200
    assert r.text == "OK" 
Example #23
Source File: web.py    From mergify-engine with Apache License 2.0 5 votes vote down vote up
def config_validator(
    data: fastapi.UploadFile = fastapi.File(...),
):  # pragma: no cover
    try:
        rules.UserConfigurationSchema(await data.read())
    except Exception as e:
        status = 400
        message = str(e)
    else:
        status = 200
        message = "The configuration is valid"

    return responses.PlainTextResponse(message, status_code=status) 
Example #24
Source File: test_webgear.py    From vidgear with Apache License 2.0 5 votes vote down vote up
def hello_webpage(request):
    """
    returns PlainTextResponse callback for hello world webpage
    """
    return PlainTextResponse("Hello, world!") 
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: app.py    From network-programmability-stream with MIT License 5 votes vote down vote up
def homepage(request) -> Response:
    return PlainTextResponse("Homepage") 
Example #27
Source File: app.py    From network-programmability-stream with MIT License 5 votes vote down vote up
def about(request) -> Response:
    return PlainTextResponse("About") 
Example #28
Source File: test_starlette_instrumentation.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def _create_starlette_app():
        def home(_):
            return PlainTextResponse("hi")

        app = applications.Starlette(
            routes=[Route("/foobar", home), Route("/user/{username}", home)]
        )
        return app 
Example #29
Source File: starlette_test.py    From swagger-ui-py with Apache License 2.0 5 votes vote down vote up
def hello_world(request):
    return PlainTextResponse('Hello World!!!') 
Example #30
Source File: starlette.py    From keycloak-client with GNU General Public License v3.0 5 votes vote down vote up
def logout(request):
    return PlainTextResponse("Logged out!")