首页 > 解决方案 > 将参数传递给基于 aiohttp 类的视图

问题描述

是否有任何简单的方法可以使用 aiohttp 将自定义参数传递给 View 实例?

这有效:

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()

但我觉得这太复杂了。使用 Tornado,您可以在实例化 Web 应用程序时将附加数据作为 dict 对象传递。

标签: aiohttp

解决方案


回答我自己的问题:

事实证明,您可以在Application实例中存储类似全局的变量,然后在请求处理程序中访问它。它在文档中有所描述:https ://docs.aiohttp.org/en/latest/web_advanced.html#application-s-config


推荐阅读