本文整理汇总了Python中starlette.applications.Starlette方法的典型用法代码示例。如果您正苦于以下问题:Python applications.Starlette方法的具体用法?Python applications.Starlette怎么用?Python applications.Starlette使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类starlette.applications
的用法示例。
在下文中一共展示了applications.Starlette方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __call__
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
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],
)
示例2: app
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
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_
示例3: app
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
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
示例4: app
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
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
示例5: test_starlette_mount
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
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
示例6: test_graphiql_endpoint_paths_when_mounted
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
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
示例7: test_tartiflette_app_as_sub_starlette_app
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
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"}}
示例8: backend_app
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
def backend_app():
return [
('flask', Flask(__name__)),
('falcon', falcon.API()),
('starlette', Starlette()),
]
示例9: get_loader_for_app
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
def get_loader_for_app(app: Any) -> Callable:
if isinstance(app, Starlette):
return from_asgi
if app.__class__.__module__.startswith("aiohttp."):
return from_aiohttp
return from_wsgi
示例10: instrument_app
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
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
示例11: _instrument
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
def _instrument(self, **kwargs):
self._original_starlette = applications.Starlette
applications.Starlette = _InstrumentedStarlette
示例12: _uninstrument
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
def _uninstrument(self, **kwargs):
applications.Starlette = self._original_starlette
示例13: _create_starlette_app
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
def _create_starlette_app():
def home(_):
return PlainTextResponse("hi")
app = applications.Starlette(
routes=[Route("/foobar", home), Route("/user/{username}", home)]
)
return app
示例14: test_instrumentation
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
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)
示例15: test_access_request_from_graphql_context
# 需要导入模块: from starlette import applications [as 别名]
# 或者: from starlette.applications import Starlette [as 别名]
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}}