我正在迁移tornado到asyncio,而且我找不到asyncio相同tornado的东西PeriodicCallback.(A PeriodicCallback有两个参数:运行的函数和调用之间的毫秒数.)
asyncio?RecursionError一会儿的风险?我有以下代码:
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/ping")
async def ping(request: Request):
print("Hello")
time.sleep(5)
print("bye")
return {"ping": "pong!"}
Run Code Online (Sandbox Code Playgroud)
如果我在本地主机上运行我的代码 - 例如http://localhost:8501/ping- 在同一浏览器窗口的不同选项卡中,我得到:
Hello
bye
Hello
bye
Run Code Online (Sandbox Code Playgroud)
代替:
Hello
Hello
bye
bye
Run Code Online (Sandbox Code Playgroud)
我已经阅读过有关使用的内容httpx,但仍然无法实现真正的并行化。有什么问题?
python asynchronous concurrent-processing python-asyncio fastapi
我正在使用 async_engine。当我尝试执行任何操作时:
async with self.async_engine.connect() as con:
query = "SELECT id, name FROM item LIMIT 50;"
result = await con.execute(f"{query}")
Run Code Online (Sandbox Code Playgroud)
我越来越:
Exception has occurred: ObjectNotExecutableError
Not an executable object: 'SELECT id, name FROM item LIMIT 50;'
Run Code Online (Sandbox Code Playgroud)
这个问题之前由用户@stilmaniac提出过,但现在已从SO 中删除。
我在谷歌搜索缓存中找到了它,这里是副本。
我有同样的问题,所以我重新询问它,但原始版本如下:
我正在尝试从元数据创建表,如下所示:
Base = declarative_base()
properties = Table(
'properties', Base.metadata,
# ...
Column('geolocation', Geography(geometry_type='POINT', srid=4326)),
# ...
)
engine = create_async_engine("postgresql+asyncpg://user:password@postgres/")
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
Run Code Online (Sandbox Code Playgroud)
给我以下错误:
sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: 'CREATE INDEX …Run Code Online (Sandbox Code Playgroud) Django 3.0 正在添加asgi/async 支持,并用它来保护在异步上下文中发出同步请求。同时,IPython 刚刚添加了顶级 async/await 支持,它似乎在默认事件循环内运行整个解释器会话。
不幸的是,这两个伟大的补充的结合意味着 jupyter notebook 中的任何 django ORM 操作都会导致SynchronousOnlyOperation异常:
SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
Run Code Online (Sandbox Code Playgroud)
正如异常消息所说,可以将每个 ORM 调用包装成sync_to_async()类似的形式:
SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
Run Code Online (Sandbox Code Playgroud)
但这不是很方便,特别是对于通常在属性查找时隐式解析的相关字段。
(我试过%autoawait off魔术,但它并没有在工作中,从快速浏览的文档,我假设这是因为ipykernels始终处于ASYNCIO循环中运行)
那么有没有办法在 django 中禁用异步上下文检查中的同步或在同步上下文中运行 ipykernel?
对于上下文:我编写了一个数据科学包,它使用 django 作为后端服务器,但还在 ORM 之上公开了一个基于 jupyter 的界面,允许您清理/注释数据、跟踪机器学习实验并在 jupyter notebook 中运行所有训练作业.
我有以下代码:
@asyncio.coroutine
def do_something_periodically():
while True:
asyncio.async(my_expensive_operation())
yield from asyncio.sleep(my_interval)
if shutdown_flag_is_set:
print("Shutting down")
break
Run Code Online (Sandbox Code Playgroud)
我运行此功能直到完成.设置关闭时会出现问题 - 该功能完成,任何挂起的任务都不会运行.(你认为这是一个错误
task: <Task pending coro=<report() running at script.py:33> wait_for=<Future pending cb=[Task._wakeup()]>>
Run Code Online (Sandbox Code Playgroud)
).如何正确安排关机?
为了给出一些上下文,我正在编写一个系统监视器,它每隔5秒从/ proc/stat读取一次,计算该时间段内的CPU使用率,然后将结果发送到服务器.我想继续安排这些监视作业,直到我收到sigterm,当我停止调度,等待所有当前作业完成,然后正常退出.
今天,我找到了一个名为trio的库,它表示自己是一个针对人类的异步API.这些词与requests' 有点类似.由于这requests是一个很好的图书馆,我想知道它的优点是什么trio.
关于它的文章不多,我只是找到一篇文章讨论curio和asyncio.令我惊讶的是,trio它本身甚至比curio(下一代古玩)更好.
阅读完一半文章后,我找不到这两个异步框架之间的核心区别.它只是给出了一些实例curio比实现更方便的例子asyncio.但底层结构几乎相同(基于回调,我认为所有异步IO框架都基于回调而没有任何异常.)
那么有人能给我一个理由我必须接受trio或者curio更好asyncio吗?或者解释一下为什么我应该选择trio而不是内置asyncio?
在异步JavaScript中,很容易并行运行任务并等待所有这些任务完成Promise.all:
async function bar(i) {
console.log('started', i);
await delay(1000);
console.log('finished', i);
}
async function foo() {
await Promise.all([bar(1), bar(2)]);
}
// This works too:
async function my_all(promises) {
for (let p of promises) await p;
}
async function foo() {
await my_all([bar(1), bar(2), bar(3)]);
}
Run Code Online (Sandbox Code Playgroud)
我试图在python中重写后者:
import asyncio
async def bar(i):
print('started', i)
await asyncio.sleep(1)
print('finished', i)
async def aio_all(seq):
for f in seq:
await f
async def main():
await aio_all([bar(i) for i in range(10)])
loop = asyncio.get_event_loop() …Run Code Online (Sandbox Code Playgroud) 我想使用生成器产量和异步函数.我读了这个主题,并编写了下一个代码:
import asyncio
async def createGenerator():
mylist = range(3)
for i in mylist:
await asyncio.sleep(1)
yield i*i
async def start():
mygenerator = await createGenerator()
for i in mygenerator:
print(i)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(start())
except KeyboardInterrupt:
loop.stop()
pass
Run Code Online (Sandbox Code Playgroud)
但我得到了错误:
SyntaxError:异步函数内的'yield'
如何在异步函数中使用yield生成器?
我有一个事件循环,它运行一些协同例程作为命令行工具的一部分.用户可以使用通常的Ctrl+ 中断工具C,此时我想在中断的事件循环后正确清理.
这是我尝试过的.
import asyncio
@asyncio.coroutine
def shleepy_time(seconds):
print("Shleeping for {s} seconds...".format(s=seconds))
yield from asyncio.sleep(seconds)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
# Side note: Apparently, async() will be deprecated in 3.4.4.
# See: https://docs.python.org/3.4/library/asyncio-task.html#asyncio.async
tasks = [
asyncio.async(shleepy_time(seconds=5)),
asyncio.async(shleepy_time(seconds=10))
]
try:
loop.run_until_complete(asyncio.gather(*tasks))
except KeyboardInterrupt as e:
print("Caught keyboard interrupt. Canceling tasks...")
# This doesn't seem to be the correct solution.
for t in tasks:
t.cancel()
finally:
loop.close()
Run Code Online (Sandbox Code Playgroud)
运行此命令并达到Ctrl+ C收益率:
$ python3 asyncio-keyboardinterrupt-example.py …Run Code Online (Sandbox Code Playgroud) 我正在尝试以下代码:
import asyncio
@asyncio.coroutine
def func_normal():
print("A")
yield from asyncio.sleep(5)
print("B")
return 'saad'
@asyncio.coroutine
def func_infinite():
i = 0
while i<10:
print("--"+str(i))
i = i+1
return('saad2')
loop = asyncio.get_event_loop()
tasks = [
asyncio.async(func_normal()),
asyncio.async(func_infinite())]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何从这些函数中获取变量中的值.我不能这样做:
asyncio.async(a = func_infinite())
Run Code Online (Sandbox Code Playgroud)
因为这会使这成为一个关键字参数.我该如何完成这项工作?
python-asyncio ×10
python ×9
python-3.x ×4
python-3.4 ×3
asynchronous ×2
python-3.5 ×2
async-await ×1
asyncpg ×1
curio ×1
django ×1
django-3.0 ×1
fastapi ×1
future ×1
ipython ×1
jupyter ×1
python-trio ×1
sqlalchemy ×1
tornado ×1
yield ×1