aiohttp - 将参数传递给基于 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 对象传递。
解决方案
回答我自己的问题:
事实证明,您可以在Application
实例中存储类似全局的变量,然后在请求处理程序中访问它。它在文档中有所描述:https ://docs.aiohttp.org/en/latest/web_advanced.html#application-s-config
推荐阅读
- vim - 自 Python 从 3.6.5 升级到 3.7.0 后,在启用 Powerline 的情况下启动 Vim 时的弃用警告
- c# - 如何在嵌套的 for 循环中打印 #
- scala - 卡夫卡生产者阻止回调
- slack - 从松弛的论坛接收未读或新帖子
- spring-cloud - 尤里卡 2.0 已停产。Netflix 现在使用什么服务发现平台?
- javascript - 2 random images but not the same one
- c# - 以编程方式将事件发布到 Outlook 日历 c# ASP.NET
- java - Firebase Recycler 查看重复数据
- php - 如何在 PHP 中获取每月的周数?
- java - 如何只允许一定数量的io异常?