def apistar(body, header): from apistar import ASyncApp, Route, http def hello(account_id) -> http.Response: content = body headers = header return http.Response(content, headers=headers) routes = [ Route('/hello/{account_id}/test', method='GET', handler=hello), ] app = ASyncApp(routes=routes) return app
from apistar import ASyncApp from .routes import license_routes from base.license import LicenseComponent __all__ = ['app'] app = ASyncApp( routes=license_routes, components=[ LicenseComponent(), ], )
raise Exception model = PuppyModel.create(**puppy) return http.JSONResponse(PuppyType(model), status_code=201) database_component = PeeweeDatabaseComponent(url="sqlite+pool://") components = [database_component] event_hooks = [PeeweeTransactionHook] routes = [Route("/puppy/", "POST", create_puppy), Route("/puppy/", "GET", list_puppies)] app = App( routes=routes, components=components, event_hooks=event_hooks, static_dir=None, docs_url=None, schema_url=None ) async_app = ASyncApp( routes=routes, components=components, event_hooks=event_hooks, static_dir=None, docs_url=None, schema_url=None ) class TestCaseEndToEnd: @pytest.fixture(params=[app, async_app]) def client(self, request): with database_component.database: database_component.database.create_tables([PuppyModel]) yield TestClient(request.param) with database_component.database: database_component.database.drop_tables([PuppyModel]) @pytest.fixture def puppy(self): return {"name": "canna"}
# coding=utf-8 from apistar import Include, Route, ASyncApp async def hello() -> str: return "Hello World!" routes = [ Route('/', 'GET', hello), ] app = ASyncApp(routes=routes) if __name__ == '__main__': app.serve('127.0.0.1', 8888, debug=True)
@classmethod def list( cls, session: Session, page: http.QueryParam, page_size: http.QueryParam, name: http.QueryParam ) -> typing.List[PuppyOutputType]: return PageNumberResponse(page=page, page_size=page_size, content=cls._filter(session=session, name=name)) routes = [Include("/puppy", "puppy", PuppyResource.routes)] sqlalchemy_component = SQLAlchemySessionComponent(url="sqlite://") components = [sqlalchemy_component] event_hooks = [SQLAlchemyTransactionHook()] app = App(routes=routes, components=components, event_hooks=event_hooks) async_app = ASyncApp(routes=routes, components=components, event_hooks=event_hooks) class TestCaseSQLAlchemyCRUD: @pytest.fixture(scope="function", params=[app, async_app]) def client(self, request): database.Base.metadata.create_all(sqlalchemy_component.engine) yield TestClient(request.param) database.Base.metadata.drop_all(sqlalchemy_component.engine) @pytest.fixture def puppy(self): return {"name": "canna"} @pytest.fixture def another_puppy(self):
from apistar import App, ASyncApp, TestClient async_app = ASyncApp(routes=[]) async_test_client = TestClient(async_app) app = App(routes=[]) test_client = TestClient(app) def test_docs(): response = test_client.get("/docs/") assert response.status_code == 200 def test_docs_async(): response = async_test_client.get("/docs/") assert response.status_code == 200
# from apistar.statics import static_routes import asyncio import time def syncwelcome(name=None): time.sleep(10) if name is None: return {'message': 'Welcome to API Star!'} return {'message': 'Welcome to API Star, %s!' % name} async def asyncwelcome(name=None): print('start---') await asyncio.sleep(10.0) print('end----') if name is None: return {'message': 'Welcome to API Star!'} return {'message': 'Welcome to API Star, %s!' % name} routes = [ Route('/', 'GET', asyncwelcome), Route('/sync', 'GET', syncwelcome), # Include('/docs', docs_routes), # Include('/static', static_routes) ] app = ASyncApp(routes=routes)
from apistar import ASyncApp, App from project.routes import routes from project.event_hooks import DataInIdentifyHook app = ASyncApp(routes=routes, event_hooks=[DataInIdentifyHook])
params["count"] = False return PageNumberResponse(**params) routes = [ Route("/limit_offset", "GET", limit_offset, "limit_offset", documented=False), Route("/page_number", "GET", page_number, "page_number", documented=False), ] app = App(routes=routes, static_dir=None, docs_url=None, schema_url=None) async_app = ASyncApp(routes=routes, static_dir=None, docs_url=None, schema_url=None) @pytest.fixture(params=[app, async_app]) def client(request): return TestClient(request.param) class TestLimitOffsetResponse: def test_default_params(self, client): response = client.get("/limit_offset") assert response.status_code == 200 assert response.json() == { "meta": { "limit": 10,
# raise exceptions.BadRequest() if not data['title']: raise exceptions.BadRequest() try: repo.update_article(article_id, data['title']) except LookupError: raise exceptions.NotFound() async def delete_article(article_id: int, password: http.Header): # if not is_auth(password): # raise exceptions.BadRequest() try: repo.delete_article(article_id) except LookupError: raise exceptions.NotFound() return http.Response('', status_code=204) routes = [ Route('/articles', method='GET', handler=list_articles), Route('/articles/{article_id}', method='GET', handler=get_article), Route('/articles', method='POST', handler=create_article), Route('/articles/{article_id}', method='POST', handler=update_article), Route('/articles/{article_id}', method='DELETE', handler=delete_article), ] app = ASyncApp(routes=routes) if __name__ == '__main__': app.serve('127.0.0.1', 8000, debug=False, schema_url=None)
def AutoASyncApp(**kwargs) -> ASyncApp: return ASyncApp(**app_args(**kwargs))
from apistar import ASyncApp from handlers import routes, WebSocketEvents app = ASyncApp( event_hooks=[WebSocketEvents], routes=routes, )
def jsonify(records): """ Parse asyncpg record response into JSON format """ list_return = [] list_keys = ['salary', 'address', 'age', 'id', 'name'] for r in records: itens = [i for i in r] itens = zip(list_keys, itens) list_return.append({ i[0]: i[1].rstrip() if type(i[1]) == str else i[1] for i in itens }) return list_return routes = [ Route('/db2', method='GET', handler=db2), ] app = ASyncApp(routes=routes) log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) if __name__ == '__main__': app.serve('127.0.0.1', 5000, use_debugger=False, use_reloader=False)