コード例 #1
0
ファイル: test_routing.py プロジェクト: batermj/starlette
def user_me(request):
    content = "User fixed me"
    return Response(content, media_type="text/plain")


def user_no_match(request):  # pragma: no cover
    content = "User fixed no match"
    return Response(content, media_type="text/plain")


def staticfiles(request):
    return Response("xxxxx", media_type="image/png")


app = Router([
    Route("/", endpoint=homepage, methods=["GET"]),
    Mount(
        "/users",
        routes=[
            Route("/", endpoint=users),
            Route("/me", endpoint=user_me),
            Route("/{username}", endpoint=user),
            Route("/nomatch", endpoint=user_no_match),
        ],
    ),
    Mount("/static", app=staticfiles),
])


@app.route("/func")
def func_homepage(request):
コード例 #2
0
ファイル: router.py プロジェクト: allsou/processos-seletivos
 def get_routes():
     return [
         Route(f'{BASE_PATH}/product',
               ProductAction().create_product,
               methods=[POST_METHOD]),
         Route(f'{BASE_PATH}/product',
               ProductAction().get_products,
               methods=[GET_METHOD]),
         Route(f'{BASE_PATH}/product/{{product_id}}',
               ProductAction().get_product,
               methods=[GET_METHOD]),
         Route(f'{BASE_PATH}/product/{{product_id}}',
               ProductAction().delete_product,
               methods=[DELETE_METHOD]),
         Route(f'{BASE_PATH}/product/{{product_id}}',
               ProductAction().update_product,
               methods=[PATCH_METHOD]),
         Route(f'{BASE_PATH}/customer',
               CustomerAction().create_customer,
               methods=[POST_METHOD]),
         Route(f'{BASE_PATH}/customer/{{customer_id}}',
               CustomerAction().get_customer,
               methods=[GET_METHOD]),
         Route(f'{BASE_PATH}/customer/{{customer_id}}',
               CustomerAction().delete_customer,
               methods=[DELETE_METHOD]),
         Route(f'{BASE_PATH}/customer/{{customer_id}}',
               CustomerAction().update_customer,
               methods=[PATCH_METHOD]),
         Route(
             f'{BASE_PATH}/customer/{{customer_id}}/favorites/{{product_id}}',
             FavoritesAction().insert_favorite,
             methods=[PUT_METHOD]),
         Route(
             f'{BASE_PATH}/customer/{{customer_id}}/favorites/{{product_id}}',
             FavoritesAction().remove_favorite,
             methods=[DELETE_METHOD])
     ]
コード例 #3
0
    blob: Blob = PACKAGES_BUCKET.blob(
        'raw/{file_name}.whl'.format(file_name=file_name))
    if not await sync_to_async(blob.exists)():
        return NOT_FOUND_RESPONSE
    expires_at_ms: datetime = datetime.now() + timedelta(
        minutes=EXPIRES_MINUTES)
    signed_url: str = await sync_to_async(blob.generate_signed_url
                                          )(expiration=expires_at_ms,
                                            credentials=SIGNING_CREDENTIALS,
                                            version='v4')
    return RedirectResponse(url=signed_url,
                            status_code=int(HTTPStatus.TEMPORARY_REDIRECT))


routes: List[BaseRoute] = [
    Route('/', endpoint=html_homepage),
    Route('/simple/', endpoint=html_simple),
    Route('/simple/{project_name}/', endpoint=html_project),
    Route('/pypi/{project_name}/json', endpoint=json_api_project),
    Route('/raw/{file_name}.whl', endpoint=whl_file),
]


class BasicAuthSecretManagerBackend(AuthenticationBackend):
    def __init__(self):
        self.client: SecretManagerServiceClient = SecretManagerServiceClient()

    async def authenticate(
            self, request: Request) -> Tuple[AuthCredentials, SimpleUser]:
        if 'Authorization' not in request.headers:
            raise AuthenticationError('Please, authenticate')
コード例 #4
0
def homepage_json(request):
    return JSONResponse({'Hello': 'World!'})


async def user_list(request):
    query = users.select()
    results = await database.fetch_all(query)
    content = [
        {
            'id': str(result['id']),
            'first_name': result['first_name']
        }
        for result in results
    ]
    return JSONResponse({'res': content})


async def startup():
    print('Ready to go')
    await database.connect()


routes = [
    Route('/', homepage),
    Route('/json', homepage_json),
    Route('/users', user_list)
]

app = Starlette(debug=True, routes=routes, on_startup=[startup])
コード例 #5
0
from starlette.routing import Route, Router

from .edits import datasheet_edits
from .view import datasheet_view

DatasheetAPI = Router([
    Route("/edits", endpoint=datasheet_edits, methods=["POST"]),
    Route("/view", endpoint=datasheet_view, methods=["GET"]),
])
コード例 #6
0
ファイル: example.py プロジェクト: alairock/sse-starlette
                _log.info(f"Disconnecting client {req.client}")
                break
            # yield dict(id=..., event=..., data=...)
            i += 1
            yield dict(data=i)
            await asyncio.sleep(0.9)
        _log.info(f"Disconnected from client {req.client}")

    return EventSourceResponse(event_publisher())


async def sse(request):
    generator = numbers(1, 25)
    return EventSourceResponse(generator)


async def home(req: Request):
    return HTMLResponse(html_sse)


routes = [
    Route("/", endpoint=home),
    Route("/numbers", endpoint=sse),
    Route("/endless", endpoint=endless),
]

app = Starlette(debug=True, routes=routes)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="trace")
コード例 #7
0
ファイル: user.py プロジェクト: lim-mil/pasteme
    task = BackgroundTask(send_email,
                          to_address=user.email,
                          username=user.username)
    return resp(code=200, background=task)


async def checkout(request: Request):
    code = request.path_params.get('code')
    username = base64.b64decode(code).decode()
    user: Optional[UserModel] = UserModel.get_or_none(
        UserModel.username == username)
    user.status = 0
    user.save()
    jwt = create_jwt_token(UserInLogin.from_orm(user))
    return resp(code=200, data={'jwt_token': jwt})


mount = Mount('/users',
              name='users',
              routes=[
                  Route('/login', login, methods=['POST'], name='login'),
                  Route('/register',
                        register,
                        methods=['POST'],
                        name='register'),
                  Route('/checkout/{code:str}',
                        checkout,
                        methods=['GET'],
                        name='checkout')
              ])
コード例 #8
0
from gqltype.contrib.starlette import GraphQLApp
from starlette.applications import Starlette
from starlette.routing import Route

from . import schema_relay, schema_simple

routes = [
    Route("/relay", GraphQLApp(schema=schema_relay.schema)),
    Route("/simple", GraphQLApp(schema=schema_simple.schema)),
]

app = Starlette(routes=routes)
コード例 #9
0
# using the low level APIs. Inspired by
# https://github.com/bokeh/bokeh/blob/master/examples/howto/server_embed/flask_gunicorn_embed.py

bokeh_app = Application(FunctionHandler(bkapp))

bokeh_tornado = BokehTornado(
    {'/bkapp': bokeh_app},
    extra_patterns=[(r'/static_assets/(.*)', StaticFileHandler, {
        'path': "static"
    })],
    extra_websocket_origins=["localhost:%s" % os.environ["BOKEH_SERVER_PORT"]])

bokeh_http = HTTPServer(bokeh_tornado)
bokeh_http.add_socket(socket)

bokeh_server = BaseServer(IOLoop.current(), bokeh_tornado, bokeh_http)
bokeh_server.start()

# Starlette App creation
app = Starlette(debug=True,
                routes=[
                    Route('/', endpoint=homepage, name='homepage_url'),
                    Mount('/static',
                          StaticFiles(directory='static'),
                          name='static'),
                    Route('/bokeh',
                          endpoint=redirect_bokeh,
                          name='bokeh_page_url'),
                    Route('/status', endpoint=server_status, name="get_status")
                ])
コード例 #10
0
ファイル: main.py プロジェクト: masahitojp/python_sandbox
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route


async def homepage(request):
    return JSONResponse({'hello': 'world'})


app = Starlette(debug=True, routes=[
    Route('/', homepage),
])
コード例 #11
0
ファイル: pql_functions.py プロジェクト: stwins60/Preql
def pql_serve_rest(state: State,
                   endpoints: T.struct,
                   port: T.int = pyvalue_inst(8080)):
    """Start a starlette server (HTTP) that exposes the current namespace as REST API

    Parameters:
        endpoints: A struct of type (string => function), mapping names to the functions.
        port: A port from which to serve the API

    Note:
        Requires the `starlette` package for Python. Run `pip install starlette`.

    Example:
        >> func index() = "Hello World!"
        >> serve_rest({index: index})
        INFO     Started server process [85728]
        INFO     Waiting for application startup.
        INFO     Application startup complete.
        INFO     Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit)
    """

    try:
        from starlette.applications import Starlette
        from starlette.responses import JSONResponse
        from starlette.routing import Route
    except ImportError:
        raise Signal.make(
            T.ImportError, None,
            "starlette not installed! Run 'pip install starlette'")

    try:
        import uvicorn
    except ImportError:
        raise Signal.make(T.ImportError, None,
                          "uvicorn not installed! Run 'pip install uvicorn'")

    port_ = cast_to_python_int(state, port)

    async def root(_request):
        return JSONResponse(list(endpoints.attrs))

    routes = [Route("/", endpoint=root)]

    for func_name, func in endpoints.attrs.items():
        path = "/" + func_name
        if func.type <= T.function:
            for p in func.params:
                path += "/{%s}" % p.name

            routes.append(
                Route(path, endpoint=_rest_func_endpoint(state, func)))
        elif func.type <= T.table:
            routes.append(
                Route(path, endpoint=_rest_table_endpoint(state, func)))
        else:
            raise Signal.make(
                T.TypeError, func,
                f"Expected a function or a table, got {func.type}")

    app = Starlette(debug=True, routes=routes)

    uvicorn.run(app, port=port_)
    return objects.null
コード例 #12
0
import typing

from starlette.routing import Route

from .endpoints import Health, Cat, Cats

ROUTES: typing.List[Route] = [
    Route("/health/", Health, methods=["GET"], name="health"),
    Route("/cat/", Cat, methods=["GET", "DELETE", "PUT"], name="Cat"),
    Route("/cats/", Cats, methods=["GET", "POST"], name="Cats"),
]
コード例 #13
0
from starlette.routing import Route

from .views import hello
from .views import main
from .views import private

routes = [
    Route("/", endpoint=main, name="main__main"),
    Route("/hello/{word:str}/", endpoint=hello, name="main__hello"),
    Route("/private/",
          endpoint=private,
          name="main__private",
          methods=["POST", "OPTIONS"]),
]
コード例 #14
0
import uvicorn

from graphql.execution.executors.asyncio import AsyncioExecutor
from starlette.applications import Starlette
from starlette.graphql import GraphQLApp
from starlette.routing import Route

from app.schema import schema

routes = [
    Route('/', GraphQLApp(
        schema=schema,
        executor_class=AsyncioExecutor
    ))
]

app = Starlette(routes=routes)

if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=9000)
コード例 #15
0
ファイル: test_routing.py プロジェクト: plizonczyk/starlette
    content = "User " + request.path_params["username"]
    return Response(content, media_type="text/plain")


def user_me(request):
    content = "User fixed me"
    return Response(content, media_type="text/plain")


def user_no_match(request):  # pragma: no cover
    content = "User fixed no match"
    return Response(content, media_type="text/plain")


app = Router([
    Route("/", endpoint=homepage, methods=["GET"]),
    Mount(
        "/users",
        routes=[
            Route("/", endpoint=users),
            Route("/me", endpoint=user_me),
            Route("/{username}", endpoint=user),
            Route("/nomatch", endpoint=user_no_match),
        ],
    ),
    Mount("/static", app=Response("xxxxx", media_type="image/png")),
])


@app.route("/func")
def func_homepage(request):
コード例 #16
0
ファイル: app.py プロジェクト: gvbgduh/starlette-cbge
from starlette.applications import Starlette
from starlette.routing import Route, Router
from starlette.schemas import SchemaGenerator

from example_app.db import database
from example_app.base_api import base_pydantic
from example_app.base_api import base_typesystem


base_pydantic_api = Router(
    [
        Route("/authors", endpoint=base_pydantic.Authors, methods=["GET", "POST"]),
        Route(
            "/authors/{id}",
            endpoint=base_pydantic.Author,
            methods=["GET", "PUT", "DELETE"],
        ),
    ]
)

base_typesystem_api = Router(
    [
        Route("/authors", endpoint=base_typesystem.Authors, methods=["GET", "POST"]),
        Route(
            "/authors/{id}",
            endpoint=base_typesystem.Author,
            methods=["GET", "PUT", "DELETE"],
        ),
    ]
)
コード例 #17
0
ファイル: helper.py プロジェクト: pmalmgren/vapor
import pickle

from starlette.endpoints import HTTPEndpoint
from starlette.routing import Route, Router
from starlette.responses import JSONResponse
import uvicorn


class Homepage(HTTPEndpoint):
    async def post(self, request):
        print(request)
        body = await request.json()
        fn = body['fn']
        resp = {'response': fn}

        return JSONResponse(resp)


app = Router([
    Route('/', endpoint=Homepage, methods=['POST']),
])

if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=9999, debug=True)
コード例 #18
0
ファイル: app.py プロジェクト: mtrunt/joplin-web
@main_app.exception_handler(500)
async def server_error(request, exc):
    """
    Return an HTTP 500 page.
    """
    template = "500.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=500)


# The API Routes
api = Router(routes=[
    Mount('/jw',
          app=Router([
              Route('/tags/', endpoint=get_tags, methods=['GET']),
              Route('/tags/', endpoint=create_tag, methods=['POST']),
              Route('/folders/', endpoint=get_folders, methods=['GET']),
              Route('/folders/', endpoint=create_folder, methods=['POST']),
              Mount('/notes',
                    app=Router([
                        Route('/', endpoint=get_notes, methods=['GET']),
                        Route('/', endpoint=create_notes, methods=['POST']),
                        Route('/{note_id}', endpoint=get_note, methods=['GET'
                                                                        ]),
                        Route('/{note_id}',
                              endpoint=update_note,
                              methods=['PATCH']),
                        Route('/{note_id}',
                              endpoint=delete_note,
                              methods=['DELETE']),
コード例 #19
0
ファイル: app.py プロジェクト: Mukeshjv9798/FRS
import sys
import uvicorn
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.staticfiles import StaticFiles
from routes import homepage, findrecipe
from middleware import middleware


app = Starlette(debug=True, routes=[
    Route('/', homepage),
    Route('/findrecipe', findrecipe, methods=["GET", "POST"])
] , middleware=middleware)

app.mount(
    '/static', StaticFiles(directory='./static/'))

if __name__ == '__main__':
    if 'serve' in sys.argv:
        uvicorn.run(app=app, host='0.0.0.0', port=5000, log_level="info")
コード例 #20
0
ファイル: web.py プロジェクト: berkayopak/ExampleVueApp
                        f"DuplicateKeyError: {data['machine_id']} already registered"
                    })
                elif data["machine_id"] not in machine_ids:
                    await websocket.send_json({
                        "error":
                        f"InvalidIDError: {data['machine_id']} is not valid"
                    })
                else:
                    registered_ids.append(data["machine_id"])

            if datetime.now() > next_message:
                next_message += timedelta(seconds=1)
                messages = generate_messages()
                for message in messages:
                    await websocket.send_json(message)
    except WebSocketDisconnect:
        await websocket.close()


middleware = [Middleware(CORSMiddleware, allow_origins=['*'])]

application = app = Starlette(debug=True,
                              routes=[
                                  WebSocketRoute('/consumption/',
                                                 consumption_endpoint),
                                  Route('/machines/', machines_endpoint),
                                  Route('/machines/{mid:int}/',
                                        machine_detail_endpoint),
                              ],
                              middleware=middleware)
コード例 #21
0
from starlette.routing import Route, Router

from ads.endpoints import (ad, ad_create, ad_delete, ad_edit, ad_images,
                           ads_list, edit_upload, filter_search, image_delete,
                           image_edit, maps, review_create, review_delete,
                           review_edit, search, upload)

ads_routes = Router([
    Route("/", endpoint=ads_list, methods=["GET", "POST"], name="ads_list"),
    Route(
        "/{id:int}/{slug:str}",
        endpoint=ad,
        methods=["GET", "POST"],
        name="ad",
    ),
    Route(
        "/create",
        endpoint=ad_create,
        methods=["GET", "POST"],
        name="ad_create",
    ),
    Route(
        "/edit/{id:int}",
        endpoint=ad_edit,
        methods=["GET", "POST"],
        name="ad_edit",
    ),
    Route(
        "/delete/{id:int}",
        endpoint=ad_delete,
        methods=["GET", "POST"],
コード例 #22
0
    return Response()


async def login(request):
    """
    A login endpoint that creates a session.
    """
    request.session.update({
        "iss": "myself",
        "user": "******",
    })
    return RedirectResponse(url=request.url_for("check"))


routes = [  # pylint: disable=invalid-name
    Route("/", endpoint=check, name="check"),
    Route("/login", endpoint=login),
]

app = Starlette(debug=True, routes=routes)  # pylint: disable=invalid-name

if JWT_ALG.startswith("HS"):
    secret_key = config(  # pylint: disable=invalid-name
        "JWT_SECRET",
        cast=Secret,
        default="secret")
else:

    if JWT_ALG.startswith("RS"):

        private_key = open(  # pylint: disable=invalid-name
コード例 #23
0
from typing import List, Dict


async def create_database_pool():
    pool: Pool = await asyncpg.create_pool(host='127.0.0.1',
                                           port=5432,
                                           user='******',
                                           password='******',
                                           database='products',
                                           min_size=6,
                                           max_size=6)
    app.state.DB = pool


async def destroy_database_pool():
    pool = app.state.DB
    await pool.close()


async def brands(request: Request) -> Response:
    connection: Pool = request.app.state.DB
    brand_query = 'SELECT brand_id, brand_name FROM brand'
    results: List[Record] = await connection.fetch(brand_query)
    result_as_dict: List[Dict] = [dict(brand) for brand in results]
    return JSONResponse(result_as_dict)


app = Starlette(routes=[Route('/brands', brands)],
                on_startup=[create_database_pool],
                on_shutdown=[destroy_database_pool])
コード例 #24
0
 def _static_file(file_path):
     return Route(
         file_path,
         lambda _: FileResponse(path=self.relative_path(f"webapp/build{file_path}")),
         name="root_static",
     )
コード例 #25
0
ファイル: server.py プロジェクト: liuxing3169/thingtalk
    async def config_routes(self):
        if isinstance(self.things, MultipleThings):
            for idx, thing in await self.things.get_things():
                await thing.set_href_prefix(f"{self.base_path}/{idx}")

            base_route = [
                Route(f"{self.base_path}", ThingsHandler),
            ]
            routes = [
                Route("/{thing_id:str}", ThingHandler),
                WebSocketRoute("/{thing_id:str}", WsThingHandler),
                Route("/{thing_id:str}/properties", PropertiesHandler),
                Route("/{thing_id:str}/properties/{property_name:str}",
                      PropertyHandler),
                Route("/{thing_id:str}/actions", ActionsHandler),
                Route("/{thing_id:str}/actions/{action_name:str}",
                      ActionHandler),
                Route("/{thing_id:str}/actions/{action_name:str}/{action_id}",
                      ActionHandler),
                Route("/{thing_id:str}/events", EventHandler),
                Route("/{thing_id:str}/events/{event_name:str}", EventHandler),
            ]
        else:
            thing = await self.things.get_thing()
            await thing.set_href_prefix(self.base_path)

            base_route = [
                Route(f"{self.base_path}", ThingHandler),
                WebSocketRoute(f"{self.base_path}", WsThingHandler),
            ]
            routes = [
                Route("/properties", PropertiesHandler),
                Route("/properties/{property_name:str}", PropertyHandler),
                Route("/actions", ActionsHandler),
                Route("/actions/{action_name:str}", ActionHandler),
                Route("/actions/{action_name:str}/{action_id:str}",
                      ActionIDHandler),
                Route("/events", EventsHandler),
                Route("/events/{event_name:str}", EventHandler),
            ]

        # should additional_routes also have prefix?
        if isinstance(self.additional_routes, list):
            routes = self.additional_routes + routes

        if self.base_path:
            routes = base_route + [
                # Route('/', homepage),
                Mount(f"{self.base_path}", routes=routes),
            ]

        return routes
コード例 #26
0
PATHS_NAR_INFO = [
    '/{drv_hash:str}.narinfo',
]
PATHS_NAR_XZ = [
    '/nar/{nar_xz_hash:str}.nar.xz',
]


APP = Starlette(
    on_startup=[
        handlers.on_startup,
    ],
    on_shutdown=[
        handlers.on_shutdown,
    ],
    routes=[
        # Handle possible .narinfo requests
        *(
            Route(path, handlers.proxy_as_narinfo, methods=['GET'])
            for path in PATHS_NAR_INFO
        ),
        # Handle possible .nar.xz requests
        *(
            Route(path, handlers.proxy_as_nar_xz, methods=['GET'])
            for path in PATHS_NAR_XZ
        ),
        # Base case, just proxy to upstream
        Route('/{path:path}', handlers.proxy_to_substituter),
    ],
)
コード例 #27
0
def build_db_app(**opts):
    """Instead of just exporting an app, we allow you to create one yourself
    such that you can add middleware to set e.g. request.state.db

    This is the main entry point for this module.

    """
    return Starlette(routes=[
        Route('/', Database),
        Route('/_changes', changes),
        Route('/_revs_diff', revs_diff, methods=['POST']),
        Route('/_ensure_full_commit', ensure_full_commit, methods=['POST']),
        Route('/_all_docs', all_docs),
        Route('/_bulk_docs', bulk_docs, methods=['POST']),
        Route('/_design/{id}', DesignDocumentEndpoint),
        Route('/_design/{id}/{attachment:path}', DesignAttachmentEndpoint),
        Route('/_local/{id}', LocalDocumentEndpoint),
        Route('/{id}', DocumentEndpoint),
        Route('/{id}/{attachment:path}', AttachmentEndpoint),
    ],
                     **opts)
コード例 #28
0
from starlette.routing import Route, Router
from accounts.views import (register, logout, login, profile, dashboard,
                            user_delete, read_notification)

accounts_routes = Router([
    Route("/login", endpoint=login, methods=["GET", "POST"], name="login"),
    Route("/register",
          endpoint=register,
          methods=["GET", "POST"],
          name="register"),
    Route("/logout", endpoint=logout, methods=["GET", "POST"], name="logout"),
    Route("/profile", endpoint=profile, methods=["GET"], name="profile"),
    Route("/dashboard", endpoint=dashboard, methods=["GET"], name="dashboard"),
    Route("/user-delete/{id:int}",
          endpoint=user_delete,
          methods=["GET", "POST"],
          name="user_delete"),
    Route("/read/{id:int}",
          endpoint=read_notification,
          methods=["GET", "POST"],
          name="read_notification"),
])
コード例 #29
0
            'request': request,
            'message': message
        })


async def verify_email_view(request: Request):
    subscription = await Subscription.get_or_none(
        token=request.query_params.get('token'))
    status_code = 400
    message = 'invalid token'
    if subscription:
        subscription.verified = True
        subscription.token = None
        await subscription.save(update_fields=('verified', 'token',
                                               'modified_at'))
        status_code = 200
        message = 'email verified successfully'
    return settings.TEMPLATE.TemplateResponse(
        name='/subscription/verify_email.html',
        status_code=status_code,
        context={
            'request': request,
            'message': message
        })


routes = (Route('/', subscribe_view,
                methods=['GET', 'POST']), Route('/verify', verify_email_view))

subscription_views = Starlette(routes=routes)
コード例 #30
0
ファイル: test_endpoints.py プロジェクト: encode/starlette
from starlette.endpoints import HTTPEndpoint, WebSocketEndpoint
from starlette.responses import PlainTextResponse
from starlette.routing import Route, Router


class Homepage(HTTPEndpoint):
    async def get(self, request):
        username = request.path_params.get("username")
        if username is None:
            return PlainTextResponse("Hello, world!")
        return PlainTextResponse(f"Hello, {username}!")


app = Router(routes=[
    Route("/", endpoint=Homepage),
    Route("/{username}", endpoint=Homepage)
])


@pytest.fixture
def client(test_client_factory):
    with test_client_factory(app) as client:
        yield client


def test_http_endpoint_route(client):
    response = client.get("/")
    assert response.status_code == 200
    assert response.text == "Hello, world!"