def setup_app(): get_schema = OpenAPIHandler( metadata=Metadata( title="Pet Store", description=__doc__, version="0.0.0", ), security_schemes=[HTTPSecurityScheme("Bearer", "bearer")], default_security_scheme="Bearer", ) get_schema = annotate(no_auth=True)(get_schema) get_docs = annotate(no_auth=True)(OpenAPIUIHandler()) return App( components=[ DatabaseComponent(), categories.CategoryManagerComponent(), tags.TagManagerComponent(), pets.PetManagerComponent(), ], middleware=[ ResponseRendererMiddleware(), auth_middleware, ], routes=[ Include("/v1/categories", categories.routes), Include("/v1/pets", pets.routes), Include("/v1/tags", tags.routes), Route("/_docs", get_docs), Route("/_schema", get_schema), ], )
def test_router_can_reverse_routes(): # Given that I have a router with some nested routes router = Router([ Include("/v1", [ Include("/accounts", [ Route("/", handler, name="get_accounts"), Route("/{account_id}", handler, name="get_account"), ]), ]), ]) # When I try to reverse a route # Then I should get back a string assert router.reverse_uri("get_accounts") == "/v1/accounts/" assert router.reverse_uri("get_account", account_id=1) == "/v1/accounts/1" # When I try to reverse a route that doesn't exist # Then a RouteNotFound error should be raised with pytest.raises(RouteNotFound): router.reverse_uri("i-dont-exist") # When I try to reverse a route that needs a particular parameter but I don't provide it # Then a RouteParamMissing error should be raised with pytest.raises(RouteParamMissing): router.reverse_uri("get_account")
def setup_app(): setup_logging() cookie_store = CookieStore(**settings.strict_get("sessions")) get_schema = OpenAPIHandler( Metadata( title="Chat", description="A simple chat app.", version="0.0.0", ), ) get_docs = OpenAPIUIHandler() app = App( components=[ AccountManagerComponent(), ChatHandlerFactoryComponent(), ChatroomListenerComponent(), ChatroomRegistryComponent(), CurrentAccountComponent(), PasswordHasherComponent(), RedisComponent(), SQLAlchemyEngineComponent(), SQLAlchemySessionComponent(), SessionComponent(cookie_store), SettingsComponent(settings), TemplatesComponent(path_to("templates")), ], middleware=[ RequestIdMiddleware(), SessionMiddleware(cookie_store), ResponseRendererMiddleware(), WebsocketsMiddleware(), SQLAlchemyMiddleware(), ], routes=[ Route("/_schema", get_schema), Route("/_docs", get_docs), Route("/", index), Route("/login", login), Route("/register", register), Include("/v1", [ Include("/accounts", accounts.routes, namespace="accounts"), Include("/chat", chat.routes, namespace="chat"), Include("/sessions", sessions.routes, namespace="sessions"), ], namespace="v1"), ], ) decorated_app = WhiteNoise(app, **settings.strict_get("whitenoise")) return decorated_app, app
def test_router_can_match_nested_routes(): # Given that I have a router with some nested routes router = Router([ Include("/v1", [ Include("/accounts", [ Route("/", handler, name="get_accounts"), Route("/{account_id}", handler, name="get_account"), ]), ]), ]) # When I match either of the routes # Then I should get back their Route objects and path params assert router.match("GET", "/v1/accounts/") assert router.match("GET", "/v1/accounts/1") # When I match a route that doesn't exist # Then I should get back None assert router.match("GET", "/v1") is None
def create_app(middleware=None, components=None, settings=None): if settings is None: settings = Settings({ 'database_engine_dsn': os.environ['SQLALCHEMY_URI'], 'identity_server': os.environ['IDENTITY_SERVER'], 'secret_key': os.environ['SECRET_KEY'], }) if middleware is None: middleware = [ ResponseRendererMiddleware(), SQLAlchemyMiddleware(), auth_middleware, ] if components is None: components = [ SettingsComponent(settings), SQLAlchemyEngineComponent(), SQLAlchemySessionComponent(), RequestSessionComponent(), AuthProviderComponent(), ManagerComponent(ChoreInstanceManager), ManagerComponent(ChoreDefinitionManager), UserProviderComponent(), ] app = App( routes=[ Route('/login', login, method='POST', name='login'), Include( '/api', routes, namespace='api', ) ], middleware=middleware, components=components, ) return app
def setup_app(): setup_logging() get_docs = OpenAPIUIHandler() get_schema = OpenAPIHandler( metadata=Metadata( title="Pets", description="", version="0.0.0", ), ) app = App( components=[ ManagerComponent(PetManager), SQLAlchemyEngineComponent(), SQLAlchemySessionComponent(), SettingsComponent(settings), TemplatesComponent(path_to("templates")), ], middleware=[ RequestIdMiddleware(), ResponseRendererMiddleware(), SQLAlchemyMiddleware(), ], routes=[ Route("/_docs", get_docs), Route("/_schema", get_schema), Route("/", index), Include("/v1/pets", pets.routes, namespace="pets"), ], ) decorated_app = WhiteNoise(app, **settings.strict_get("whitenoise")) return decorated_app, app
def delete_todo(todo_id: int, todo_manager: TodoManager): todo_manager.delete_todo(todo_id) return ( HTTP_202, APIResponse(status=202, message=f"Delete request for todo: {todo_id} accepted"), ) def get_todo_by_id(todo_id: int, todo_manager: TodoManager) -> Todo: try: _todo = todo_manager.get_todo_by_id(todo_id) except EntityNotFound as err: raise HTTPError(HTTP_404, APIResponse(status=404, message=err.message) ) return _todo def update_todo(todo_id: int, todo: Todo, todo_manager: TodoManager) -> Todo: return todo_manager.update_todo(todo_id, todo) todo_routes = Include("/todos", [ Route("", list_todos, method="GET"), Route("", create_todo, method="POST"), Route("/{todo_id}", delete_todo, method="DELETE"), Route("/{todo_id}", get_todo_by_id, method="GET"), Route("/{todo_id}", update_todo, method="PATCH") ])
title="Emeeting API", description="An API for managing your room meetings.", version="0.0.1", )) get_docs = OpenAPIUIHandler() """ Add middlewares """ middlewares = [prometheus_middleware, ResponseRendererMiddleware()] """ Include or add routes """ routes = [ Route("/", get_docs), Route("/schema", get_schema), Route("/metrics", expose_metrics), Include("/v1/rooms", routes=room.routes), Include("/v1/meetings", routes=meeting.routes), ] """ Start application """ app = App(routes=routes, middleware=middlewares) app = CORS(app, headers="*", methods="*", origin="*", maxage="86400") log.info("Start application successfully.")
return Kitten(id=kitten_ob.id, name=kitten_ob.name) app = App( components=[ TOMLSettingsComponent(), SQLAlchemyEngineComponent(), SQLAlchemySessionComponent(), ], middleware=[ ResponseRendererMiddleware([JSONRenderer()]), SQLAlchemyMiddleware(), ], routes=[ Include("/v1/kittens", [ Route("", list_kittens), Route("", create_kitten, method="POST"), Route("/{kitten_id}", get_kitten), ]), ], ) def initdb(engine_data: EngineData): Base.metadata.create_all(engine_data.engine) # Initialize the DB by injecting EngineData into initdb and calling it. resolver = app.injector.get_resolver() resolver.resolve(initdb)()
get_docs = OpenAPIUIHandler() get_schema = OpenAPIHandler( metadata=Metadata( title="Todo API", description="An API for managing todos.", version="0.0.0", ), security_schemes=[ HTTPSecurityScheme("default", "bearer"), ], default_security_scheme="default", ) routes: List[Union[Route, Include]] = [ Include("/v1/todos", [ Route("/", list_todos), Route("/", create_todo, method="POST"), Route("/{todo_id}", get_todo), Route("/{todo_id}", delete_todo, method="DELETE"), ]), Route("/_docs", get_docs), Route("/_schema", get_schema), ] app = App( components=components, middleware=middleware, routes=routes, )
get_schema = OpenAPIHandler( metadata=Metadata( title="Pet Store", description="An example application that generates OpenAPI schema.", version="0.1.0", ), security_schemes=[ HTTPSecurityScheme("Bearer Authorization", "bearer") ], default_security_scheme="Bearer Authorization", ) app = App( routes=[ Include("/v0/pets", [ Route("", add_pet_deprecated, method="POST"), ]), Include("/v1/pets", [ Route("", list_pets), Route("", add_pet, method="POST"), Include("/{pet_id}", [ Route("", update_pet, method="PUT"), Route("", delete_pet, method="DELETE"), Route("/photos", add_photo, method="POST"), ]), ]), Include("/v1/users", [ Route("/current/settings", update_settings, method="PUT"), ]), Route("/schema.json", get_schema, name="schema"), Route("/docs", OpenAPIUIHandler("schema")),
is_cacheable = True is_singleton = True def can_handle_parameter(self, parameter: Parameter) -> bool: return parameter.annotation is TodoManager def resolve(self, db: DB) -> TodoManager: return TodoManager(db) def list_todos(todo_manager: TodoManager) -> List[Todo]: return todo_manager.get_all() def create_todo(todo: Todo, todo_manager: TodoManager) -> Todo: return todo_manager.save(todo) app = App( components=[ DBComponent(), TodoManagerComponent(), ], routes=[ Include("/todos", [ Route("/", list_todos), Route("/", create_todo, method="POST"), ]), ], )
content=content, headers={"content-type": "text/plain"}) components: List[Component] = [DBComponent(), TodoManagerComponent()] middleware: List[Middleware] = [CORSMiddleware(), ResponseRendererMiddleware()] renderers: List[ResponseRenderer] = [JSONRenderer(), PlainTextRenderer()] routes: List[Union[Route, Include]] = [ Include( "/v1/todos", [ Route("/", options_todos, method="OPTIONS"), Route("/", list_todos), Route("/", create_todo, method="POST"), Route("/", delete_all, method="DELETE"), Route("/{todo_id}", options_todo, method="OPTIONS"), Route("/{todo_id}", get_todo), Route("/{todo_id}", delete_todo, method="DELETE"), Route("/{todo_id}", update_todo, method="PATCH"), ], ) ] app = App(components=components, middleware=middleware, renderers=renderers, routes=routes)
components: List[Component] = [ # TOMLSettingsComponent(), SQLAlchemyEngineComponent(), SQLAlchemySessionComponent(), SettingsComponent(settings.SETTINGS) ] middleware: List[Middleware] = [ ResponseRendererMiddleware(), SQLAlchemyMiddleware(), ] routes: List[Union[Route, Include]] = [ Include("/api/v1/users", [ Route("", list_users), Route("", create_user, method="POST"), Route("/{user_id}", delete_user, method="DELETE"), Route("/{user_id}", get_user), ]), Include("/api/v1/comments", [ Route("", list_comments), Route("", create_comment, method="POST"), Route("/{comment_id}", delete_comment, method="DELETE"), Route("/{comment_id}", get_comment), ]), Route("/_docs", get_docs), Route("/_schema", get_schema), ]
except IntegrityError as err: # noqa: F841 raise HTTPError( HTTP_409, APIResponse( status=409, message= f"User email {user.email} or {user.display_name} already in use.", ), ) headers = {"Location": _user.href} return HTTP_201, _user, headers def get_user_by_display_name( display_name: str, user_manager: UserManager) -> Union[User, APIResponse]: try: user = user_manager.get_user_by_display_name(display_name) except EntityNotFound as err: raise HTTPError(HTTP_404, APIResponse(status=404, message=err.message)) return user user_routes = Include( "/users", [ Route("", create_user, method="POST"), Route("/{display_name}", get_user_by_display_name, method="GET"), ], )