Created
October 8, 2020 00:09
-
-
Save vane/4ee03a2453f1a1aea8024934f3655a57 to your computer and use it in GitHub Desktop.
aiohttp register routes from file with prefix to the application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import logging | |
from aiohttp import web, hdrs | |
import test_api | |
__version__ = '0.1' | |
def register_routes(router: web.UrlDispatcher, routes: web.RouteTableDef, prefix: str = ''): | |
for route in routes: # type: web.RouteDef | |
if route.method in hdrs.METH_ALL: | |
reg = getattr(router, 'add_'+route.method.lower()) | |
reg(f'{prefix}{route.path}', route.handler, **route.kwargs) | |
else: | |
router.add_route(route.method, f'{prefix}{route.path}', route.handler, **route.kwargs) | |
app = web.Application() | |
register_routes(app.router, test_api.routes, prefix=f'/v{__version__}') | |
web.run_app(app, port=8080) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from aiohttp import web | |
routes = web.RouteTableDef() | |
@routes.get('/test') | |
async def get_handler(req): | |
return web.json_response({}) | |
@routes.get('/test/{test_id}') | |
async def get_one_handler(req): | |
test_id = req.match_info['test_id'] | |
return web.json_response({}) | |
@routes.post('/test') | |
async def post_handler(req): | |
return web.json_response({}) | |
@routes.put('/test/{test_id}') | |
async def put_handler(req): | |
test_id = req.match_info['test_id'] | |
return web.json_response({}) | |
@routes.delete('/test/{test_id}') | |
async def delete_handler(req): | |
test_id = req.match_info['test_id'] | |
return web.json_response({}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example
curl http://localhost:8080/v0.1/test