Python starlette.applications.Starlette() Examples
The following are 30
code examples of starlette.applications.Starlette().
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.applications
, or try the search function
.
Example #1
Source File: webgear.py From vidgear with Apache License 2.0 | 6 votes |
def __call__(self): """ Implements a custom Callable method for WebGear application. """ # validate routing tables assert not (self.routes is None), "Routing tables are NoneType!" if not isinstance(self.routes, list) or not all( x in self.routes for x in self.__rt_org_copy ): raise RuntimeError("Routing tables are not valid!") # initiate stream if self.__logging: logger.debug("Initiating Video Streaming.") self.stream.start() # return Starlette application if self.__logging: logger.debug("Running Starlette application.") return Starlette( debug=(True if self.__logging else False), routes=self.routes, exception_handlers=self.__exception_handlers, on_shutdown=[self.shutdown], )
Example #2
Source File: test_end_to_end.py From starlette-prometheus with GNU General Public License v3.0 | 6 votes |
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_asgi.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
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 #4
Source File: test_mount.py From tartiflette-asgi with MIT License | 6 votes |
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 #5
Source File: test_mount.py From tartiflette-asgi with MIT License | 6 votes |
def test_graphiql_endpoint_paths_when_mounted( engine: Engine, mount_path: str ) -> None: graphql = TartifletteApp(engine=engine, graphiql=True, subscriptions=True) app = Starlette(routes=[Mount(mount_path, graphql)], on_startup=[graphql.startup]) async with get_client(app) as client: response = await client.get(mount_path, headers={"accept": "text/html"}) assert response.status_code == 200 graphql_endpoint = mount_path + "/" assert f"var graphQLEndpoint = `{graphql_endpoint}`;" in response.text subscriptions_endpoint = mount_path + "/subscriptions" assert f"var subscriptionsEndpoint = `{subscriptions_endpoint}`;" in response.text
Example #6
Source File: test_mount.py From tartiflette-asgi with MIT License | 6 votes |
def test_starlette_mount(engine: Engine, mount_path: str, path: str) -> None: kwargs = omit_none({"engine": engine, "path": path}) graphql = TartifletteApp(**kwargs) routes = [Mount(mount_path, graphql)] app = Starlette(routes=routes, on_startup=[graphql.startup]) query = "{ hello }" full_path = mount_path.rstrip("/") + ("/" if path is None else path) assert "//" not in full_path url = f"{full_path}?query={query}" async with get_client(app) as client: response = await client.get(url) graphiql_response = await client.get(url, headers={"accept": "text/html"}) assert response.status_code == 200 assert response.json() == {"data": {"hello": "Hello stranger"}} assert graphiql_response.status_code == 200 assert full_path in graphiql_response.text
Example #7
Source File: starlette_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #8
Source File: metrics.py From community-playground with Apache License 2.0 | 5 votes |
def __init__(self, errormiddleware, webapp: Starlette): BaseHTTPMiddleware.__init__(self, errormiddleware) self.webapp = webapp
Example #9
Source File: metrics.py From community-playground with Apache License 2.0 | 5 votes |
def __init__(self, errormiddleware, webapp: Starlette): BaseHTTPMiddleware.__init__(self, errormiddleware) self.webapp = webapp
Example #10
Source File: metrics.py From community-playground with Apache License 2.0 | 5 votes |
def configure_prometheus_metrics_exporter(app: Starlette): app.add_middleware(MetricsMiddleware, webapp=app) app.registry = Registry() const_labels = { "host": socket.gethostname(), "name": "service2", "version": "1" } app.counter_gauge = Gauge( "counter", "Current count.", const_labels=const_labels) app.registry.register(app.counter_gauge) app.svc_requests_total = Counter( "svc_requests_total", "Count of service HTTP requests", const_labels=const_labels) app.registry.register(app.svc_requests_total) app.svc_responses_total = Counter( "svc_responses_total", "Count of service HTTP responses", const_labels=const_labels) app.registry.register(app.svc_responses_total) app.svc_internal_error_total = Counter( "svc_internal_error_total", "Histogram of internal errors by method, path and type of error", const_labels=const_labels) app.registry.register(app.svc_internal_error_total)
Example #11
Source File: metrics.py From community-playground with Apache License 2.0 | 5 votes |
def __init__(self, errormiddleware, webapp: Starlette): BaseHTTPMiddleware.__init__(self, errormiddleware) self.webapp = webapp
Example #12
Source File: metrics.py From community-playground with Apache License 2.0 | 5 votes |
def configure_prometheus_metrics_exporter(app: Starlette): app.add_middleware(MetricsMiddleware, webapp=app) app.registry = Registry() const_labels = { "host": socket.gethostname(), "name": "service2", "version": "4" } app.counter_gauge = Gauge( "counter", "Current count.", const_labels=const_labels) app.registry.register(app.counter_gauge) app.svc_requests_total = Counter( "svc_requests_total", "Count of service HTTP requests", const_labels=const_labels) app.registry.register(app.svc_requests_total) app.svc_responses_total = Counter( "svc_responses_total", "Count of service HTTP responses", const_labels=const_labels) app.registry.register(app.svc_responses_total) app.svc_internal_error_total = Counter( "svc_internal_error_total", "Histogram of internal errors by method, path and type of error", const_labels=const_labels) app.registry.register(app.svc_internal_error_total)
Example #13
Source File: metrics.py From community-playground with Apache License 2.0 | 5 votes |
def configure_prometheus_metrics_exporter(app: Starlette): app.add_middleware(MetricsMiddleware, webapp=app) app.registry = Registry() const_labels = { "host": socket.gethostname(), "name": "service2", "version": "2" } app.counter_gauge = Gauge( "counter", "Current count.", const_labels=const_labels) app.registry.register(app.counter_gauge) app.svc_requests_total = Counter( "svc_requests_total", "Count of service HTTP requests", const_labels=const_labels) app.registry.register(app.svc_requests_total) app.svc_responses_total = Counter( "svc_responses_total", "Count of service HTTP responses", const_labels=const_labels) app.registry.register(app.svc_responses_total) app.svc_internal_error_total = Counter( "svc_internal_error_total", "Histogram of internal errors by method, path and type of error", const_labels=const_labels) app.registry.register(app.svc_internal_error_total)
Example #14
Source File: metrics.py From community-playground with Apache License 2.0 | 5 votes |
def configure_prometheus_metrics_exporter(app: Starlette): app.add_middleware(MetricsMiddleware, webapp=app) app.registry = Registry() const_labels = { "host": socket.gethostname(), "name": "service1", "version": "3" } app.counter_gauge = Gauge( "counter", "Current count.", const_labels=const_labels) app.registry.register(app.counter_gauge) app.svc_requests_total = Counter( "svc_requests_total", "Count of service HTTP requests", const_labels=const_labels) app.registry.register(app.svc_requests_total) app.svc_responses_total = Counter( "svc_responses_total", "Count of service HTTP responses", const_labels=const_labels) app.registry.register(app.svc_responses_total) app.svc_internal_error_total = Counter( "svc_internal_error_total", "Histogram of internal errors by method, path and type of error", const_labels=const_labels) app.registry.register(app.svc_internal_error_total)
Example #15
Source File: metrics.py From community-playground with Apache License 2.0 | 5 votes |
def configure_prometheus_metrics_exporter(app: Starlette): app.add_middleware(MetricsMiddleware, webapp=app) app.registry = Registry() const_labels = { "host": socket.gethostname(), "name": "service2", "version": "3" } app.counter_gauge = Gauge( "counter", "Current count.", const_labels=const_labels) app.registry.register(app.counter_gauge) app.svc_requests_total = Counter( "svc_requests_total", "Count of service HTTP requests", const_labels=const_labels) app.registry.register(app.svc_requests_total) app.svc_responses_total = Counter( "svc_responses_total", "Count of service HTTP responses", const_labels=const_labels) app.registry.register(app.svc_responses_total) app.svc_internal_error_total = Counter( "svc_internal_error_total", "Histogram of internal errors by method, path and type of error", const_labels=const_labels) app.registry.register(app.svc_internal_error_total)
Example #16
Source File: metrics.py From community-playground with Apache License 2.0 | 5 votes |
def __init__(self, errormiddleware, webapp: Starlette): BaseHTTPMiddleware.__init__(self, errormiddleware) self.webapp = webapp
Example #17
Source File: metrics.py From community-playground with Apache License 2.0 | 5 votes |
def configure_prometheus_metrics_exporter(app: Starlette): app.add_middleware(MetricsMiddleware, webapp=app) app.registry = Registry() const_labels = { "host": socket.gethostname(), "name": "service1", "version": "1" } app.counter_gauge = Gauge( "counter", "Current count.", const_labels=const_labels) app.registry.register(app.counter_gauge) app.svc_requests_total = Counter( "svc_requests_total", "Count of service HTTP requests", const_labels=const_labels) app.registry.register(app.svc_requests_total) app.svc_responses_total = Counter( "svc_responses_total", "Count of service HTTP responses", const_labels=const_labels) app.registry.register(app.svc_responses_total) app.svc_internal_error_total = Counter( "svc_internal_error_total", "Histogram of internal errors by method, path and type of error", const_labels=const_labels) app.registry.register(app.svc_internal_error_total)
Example #18
Source File: metrics.py From community-playground with Apache License 2.0 | 5 votes |
def configure_prometheus_metrics_exporter(app: Starlette): app.add_middleware(MetricsMiddleware, webapp=app) app.registry = Registry() const_labels = { "host": socket.gethostname(), "name": "service1", "version": "2" } app.counter_gauge = Gauge( "counter", "Current count.", const_labels=const_labels) app.registry.register(app.counter_gauge) app.svc_requests_total = Counter( "svc_requests_total", "Count of service HTTP requests", const_labels=const_labels) app.registry.register(app.svc_requests_total) app.svc_responses_total = Counter( "svc_responses_total", "Count of service HTTP responses", const_labels=const_labels) app.registry.register(app.svc_responses_total) app.svc_internal_error_total = Counter( "svc_internal_error_total", "Histogram of internal errors by method, path and type of error", const_labels=const_labels) app.registry.register(app.svc_internal_error_total)
Example #19
Source File: metrics.py From community-playground with Apache License 2.0 | 5 votes |
def __init__(self, errormiddleware, webapp: Starlette): BaseHTTPMiddleware.__init__(self, errormiddleware) self.webapp = webapp
Example #20
Source File: test_spec.py From spectree with Apache License 2.0 | 5 votes |
def backend_app(): return [ ('flask', Flask(__name__)), ('falcon', falcon.API()), ('starlette', Starlette()), ]
Example #21
Source File: main.py From community-playground with Apache License 2.0 | 5 votes |
def message(request): message = f"Hello world! From Starlette running on Uvicorn with Gunicorn in Alpine." return JSONResponse({"message": message, "version": version})
Example #22
Source File: main.py From uvicorn-gunicorn-starlette-docker with MIT License | 5 votes |
def homepage(request): message = f"Hello world! From Starlette running on Uvicorn with Gunicorn. Using Python {version}" return JSONResponse({"message": message})
Example #23
Source File: test_middleware.py From starlette-jwt with BSD 3-Clause "New" or "Revised" License | 5 votes |
def create_app(): app = Starlette() app.add_route("/auth", with_auth, methods=["GET"]) app.add_route("/no-auth", without_auth, methods=["GET"]) app.add_websocket_route("/ws-auth", ws_with_auth) app.add_websocket_route("/ws-no-auth", ws_without_auth) return app
Example #24
Source File: test_mount.py From tartiflette-asgi with MIT License | 5 votes |
def test_must_register_startup_handler(engine: Engine) -> None: graphql = TartifletteApp(engine=engine) app = Starlette(routes=[Mount("/graphql", graphql)], on_startup=[]) async with get_client(app) as client: with pytest.raises(RuntimeError) as ctx: await client.get("/graphql") error = str(ctx.value).lower() assert "hint" in error assert "starlette example" in error assert ".add_event_handler" in error assert "'startup'" in error assert ".startup" in error
Example #25
Source File: test_context.py From tartiflette-asgi with MIT License | 5 votes |
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 #26
Source File: test_starlette_instrumentation.py From opentelemetry-python with Apache License 2.0 | 5 votes |
def test_instrumentation(self): """Verify that instrumentation methods are instrumenting and removing as expected. """ instrumentor = otel_starlette.StarletteInstrumentor() original = applications.Starlette instrumentor.instrument() try: instrumented = applications.Starlette self.assertIsNot(original, instrumented) finally: instrumentor.uninstrument() should_be_original = applications.Starlette self.assertIs(original, should_be_original)
Example #27
Source File: test_starlette_instrumentation.py From opentelemetry-python with Apache License 2.0 | 5 votes |
def _create_starlette_app(): def home(_): return PlainTextResponse("hi") app = applications.Starlette( routes=[Route("/foobar", home), Route("/user/{username}", home)] ) return app
Example #28
Source File: __init__.py From opentelemetry-python with Apache License 2.0 | 5 votes |
def _uninstrument(self, **kwargs): applications.Starlette = self._original_starlette
Example #29
Source File: __init__.py From opentelemetry-python with Apache License 2.0 | 5 votes |
def _instrument(self, **kwargs): self._original_starlette = applications.Starlette applications.Starlette = _InstrumentedStarlette
Example #30
Source File: __init__.py From opentelemetry-python with Apache License 2.0 | 5 votes |
def instrument_app(app: applications.Starlette): """Instrument a previously instrumented Starlette application. """ if not getattr(app, "is_instrumented_by_opentelemetry", False): app.add_middleware( OpenTelemetryMiddleware, span_details_callback=_get_route_details, ) app.is_instrumented_by_opentelemetry = True