Skip to content

Instantly share code, notes, and snippets.

@vane
Created October 8, 2020 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vane/4ee03a2453f1a1aea8024934f3655a57 to your computer and use it in GitHub Desktop.
Save vane/4ee03a2453f1a1aea8024934f3655a57 to your computer and use it in GitHub Desktop.
aiohttp register routes from file with prefix to the application
#!/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)
#!/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({})
@vane
Copy link
Author

vane commented Oct 8, 2020

example curl http://localhost:8080/v0.1/test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment