将未来状态直接存储在应用程序对象上是否可以?以下示例
import asyncio
async def background():
await asyncio.sleep(1)
print('Doing something useful in the background')
await asyncio.sleep(1)
@aiohttp_jinja2.template('loading.html')
async def loading(request):
app = request.app
task = getattr(app, 'task_obj', None)
if task is None:
task = asyncio.ensure_future(background())
callback = partial(done_refresh, app)
task.add_done_callback(callback)
app.task_obj = task
def done_refresh(app, future):
if hasattr(app, 'task_obj'):
# Nice! Task is done
del app.refreshing
exc = future.exception()
if exc is not None:
# Task has some exception
print('Failed to update: %s', exc)
通常,我在Redis中存储了一些像in_progress
这样的标记,然后从我想要的任何函数中检查该值,但是这样我丢失了Task
个对象本身并且无法访问有用的数据像异常信息。
处理此类案件的常用方法是什么?
答案 0 :(得分:3)
您的方法非常有意义,除了任务应存储在aiohttp应用程序上下文中,而不是设置为属性(app['task_obj'] = ...
而不是app.task_obj = ...
)
另见https://docs.aiohttp.org/en/stable/web_advanced.html#data-sharing-aka-no-singletons-please