0

Is there any simple way to pass custom arguments to View instances with aiohttp ?

This works:

import aiohttp.web
import functools

class Parent():
    def __init__(self, val):
        self.var = val

class BaseView(aiohttp.web.View):
    def __init__(self, *args, **kwargs):
        self.parent = kwargs.pop("parent")
        super().__init__(*args, **kwargs)

class Handler(BaseView):
    async def get(self):
        return aiohttp.web.Response(text=self.parent.var)

def partial_class(cls, *args, **kwargs):
    class NewCls(cls):
        __init__ = functools.partialmethod(cls.__init__, *args, **kwargs)
    return NewCls

def main():
    parent = Parent("blablabla")
    app = aiohttp.web.Application()
    # New method with args
    app.router.add_view_with_args = functools.partial(
        lambda this, path, handler, d: this.add_view(path, partial_class(handler, **d)),
        app.router,
    )
    # Tornado-style
    app.router.add_view_with_args("/test", Handler, {"parent": parent})
    aiohttp.web.run_app(app)

main()

But I feel like this is overcomplicated. With Tornado, you can pass additionnal data as a dict object when you instanciate your web Application.

NicoAdrian
  • 946
  • 1
  • 7
  • 18

1 Answers1

1

Answering my own question:

It turns out that you are allowed to store global-like variables in an Application instance and then access it in the request handler. It is described in the docs: https://docs.aiohttp.org/en/latest/web_advanced.html#application-s-config

NicoAdrian
  • 946
  • 1
  • 7
  • 18