【发布时间】:2019-11-30 19:15:03
【问题描述】:
Django 3.0 正在添加asgi / async support and with it a guard around making synchronous requests in an async context。同时,IPython just added top level async/await support,它似乎在默认事件循环内运行整个解释器会话。
不幸的是,这两个伟大的加法相结合意味着 jupyter notebook 中的任何 django ORM 操作都会导致 SynchronousOnlyOperation 异常:
SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
正如异常消息所说,可以将每个 ORM 调用包装在 sync_to_async() 中,例如:
images = await sync_to_async(Image.objects.all)()
但这不是很方便,特别是对于通常会在属性查找时隐式解析的相关字段。
(我尝试了%autoawait off 魔术,但它不起作用,快速浏览the docs 我假设这是因为 ipykernels 总是在 asyncio 循环中运行)
那么有没有办法在 django 中禁用异步上下文检查中的同步或在同步上下文中运行 ipykernel?
对于上下文:我编写了一个数据科学包,它使用 django 作为后端服务器,但还在 ORM 之上公开了一个基于 jupyter 的接口,允许您清理/注释数据、跟踪机器学习实验和运行训练作业一个 jupyter 笔记本。
【问题讨论】:
标签: django ipython jupyter python-asyncio django-3.0