我正在尝试aiohttp.ClientSession
在我的浮士德应用程序内部创建一个,这样我就可以重用它,而无需一遍又一遍地提供身份验证标头。如果我继承faust.app
class FaustApplication(faust.App):
jcm_session: Optional[aiohttp.ClientSession] = None
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.aiohttp_session = aiohttp.ClientSession(
base_url='REDACTED',
headers={
'Authorization': f'{get_credentials()}',
'Content-Type': 'application/json',
},
)
然后还定义一个测试视图(应该从该会话中定义的服务中获取一些数据):
@app.page('/test')
async def test(self, request):
res = await app.aiohttp_session.get('/api/test/')
# do some post-processing with res
return res
当我尝试使用它时出现以下错误:
[2021-11-08 09:08:48,165] [4221] [ERROR] Error handling request
Traceback (most recent call last):
File "/home/username/git/projectname/.venv/lib/python3.7/site-packages/aiohttp/web_protocol.py", line 430, in _handle_request
resp = await request_handler(request)
File "/home/username/git/projectname/.venv/lib/python3.7/site-packages/aiohttp/web_app.py", line 504, in _handle
resp = await handler(request)
File "/home/username/git/projectname/.venv/lib/python3.7/site-packages/faust/web/drivers/aiohttp.py", line 247, in _dispatch
return await handler(request)
File "/home/username/git/projectname/.venv/lib/python3.7/site-packages/faust/web/views.py", line 82, in __call__
return await self.dispatch(request)
File "/home/username/git/projectname/.venv/lib/python3.7/site-packages/faust/web/views.py", line 98, in dispatch
response = await method(cast(Request, request), **kwargs)
File "/home/username/git/projectname/worker/actions/config_backup.py", line 40, in get_config_backup
response = await app.aiohttp_session.get('/api/test')
File "/home/username/git/projectname/.venv/lib/python3.7/site-packages/aiohttp/client.py", line 466, in _request
with timer:
File "/home/username/git/projectname/.venv/lib/python3.7/site-packages/aiohttp/helpers.py", line 699, in __enter__
"Timeout context manager should be used " "inside a task"
RuntimeError: Timeout context manager should be used inside a task
如何让我的 HTTP 会话在 faust 创建的视图中可用?请注意,如果它被代理或计时器调用,但不是从视图调用,它会起作用。可能视图有自己的循环,但我不确定这里的最佳做法是什么。
附加问题:构造函数是初始化该会话的最佳位置吗?我试图有一个self.on_startup_finished
方法,但由于某种原因它永远不会被调用。
谢谢。