routing - Routing utilities

Routing utilities.

class aiohttp_utils.routing.ResourceRouter[source]

Router with an add_resource() method for registering method-based handlers, a.k.a “resources”. Includes all the methods aiohttp.web.UrlDispatcher with the addition of add_resource.

Example:

from aiohttp import web
from aiohttp_utils.routing import ResourceRouter

app = web.Application(router=ResourceRouter())

class IndexResource:

    async def get(self, request):
        return web.Response(body=b'Got it', content_type='text/plain')

    async def post(self, request):
        return web.Response(body=b'Posted it', content_type='text/plain')


app.router.add_resource_object('/', IndexResource())

# Normal function-based handlers still work
async def handler(request):
    return web.Response()

app.router.add_route('GET', '/simple', handler)

By default, handler names will be registered with the name <ClassName>:<method>.

app.router['IndexResource:post'].url() == '/'

You can override the default names by passing a names dict to add_resource.

app.router.add_resource_object('/', IndexResource(), names={'get': 'index_get'})
app.router['index_get'].url() == '/'
add_resource_object(path: str, resource, methods: tuple = (), names: collections.abc.Mapping = None)[source]

Add routes by an resource instance’s methods.

Parameters:
  • path (str) – route path. Should be started with slash ('/').
  • resource – A “resource” instance. May be an instance of a plain object.
  • methods (tuple) – Methods (strings) to register.
  • names (Mapping) – Dictionary of name overrides.
aiohttp_utils.routing.add_route_context(app: aiohttp.web_app.Application, module=None, url_prefix: str = None, name_prefix: str = None)[source]

Context manager which yields a function for adding multiple routes from a given module.

Example:

# myapp/articles/views.py
async def list_articles(request):
    return web.Response(b'article list...')

async def create_article(request):
    return web.Response(b'created article...')
# myapp/app.py
from myapp.articles import views

with add_route_context(app, url_prefix='/api/', name_prefix='articles') as route:
    route('GET', '/articles/', views.list_articles)
    route('POST', '/articles/', views.create_article)

app.router['articles.list_articles'].url()  # /api/articles/

If you prefer, you can also pass module and handler names as strings.

with add_route_context(app, module='myapp.articles.views',
                       url_prefix='/api/', name_prefix='articles') as route:
    route('GET', '/articles/', 'list_articles')
    route('POST', '/articles/', 'create_article')
Parameters:
  • app (Application) – Application to add routes to.
  • module – Import path to module (str) or module object which contains the handlers.
  • url_prefix (str) – Prefix to prepend to all route paths.
  • name_prefix (str) – Prefix to prepend to all route names.
aiohttp_utils.routing.add_resource_context(app: aiohttp.web_app.Application, module=None, url_prefix: str = None, name_prefix: str = None, make_resource=<function <lambda>>)[source]

Context manager which yields a function for adding multiple resources from a given module to an app using ResourceRouter.

Example:

# myapp/articles/views.py
class ArticleList:
    async def get(self, request):
        return web.Response(b'article list...')

class ArticleDetail:
    async def get(self, request):
        return web.Response(b'article detail...')
# myapp/app.py
from myapp.articles import views

with add_resource_context(app, url_prefix='/api/') as route:
    route('/articles/', views.ArticleList())
    route('/articles/{pk}', views.ArticleDetail())

app.router['ArticleList:get'].url()  # /api/articles/
app.router['ArticleDetail:get'].url(pk='42')  # /api/articles/42

If you prefer, you can also pass module and class names as strings.

with add_resource_context(app, module='myapp.articles.views',
                          url_prefix='/api/') as route:
    route('/articles/', 'ArticleList')
    route('/articles/{pk}', 'ArticleDetail')

Note

If passing class names, the resource classes will be instantiated with no arguments. You can change this behavior by overriding make_resource.

# myapp/authors/views.py
class AuthorList:
    def __init__(self, db):
        self.db = db

    async def get(self, request):
        # Fetch authors from self.db...
# myapp/app.py
from myapp.database import db

with add_resource_context(app, module='myapp.authors.views',
                        url_prefix='/api/',
                        make_resource=lambda cls: cls(db=db)) as route:
    route('/authors/', 'AuthorList')
Parameters:
  • app (Application) – Application to add routes to.
  • resource – Import path to module (str) or module object which contains the resource classes.
  • url_prefix (str) – Prefix to prepend to all route paths.
  • name_prefix (str) – Prefix to prepend to all route names.
  • make_resource – Function which receives a resource class and returns a resource instance.