有时需要发生一些非关键的异步操作,但我不想等待它完成.在Tornado的协程实现中,您可以通过简单地省略yield关键字来"触发并忘记"异步功能.
我一直试图弄清楚如何使用Python 3.5中发布的新async/ await语法来"解雇" .例如,简化的代码段:
async def async_foo():
print("Do some stuff asynchronously here...")
def bar():
async_foo() # fire and forget "async_foo()"
bar()
Run Code Online (Sandbox Code Playgroud)
但是会发生什么,bar()从不执行,而是我们得到运行时警告:
RuntimeWarning: coroutine 'async_foo' was never awaited
async_foo() # fire and forget "async_foo()"
Run Code Online (Sandbox Code Playgroud) 我正在构建一个 SMTP 服务器,并aiosmtpd使用这些示例作为构建的基础。下面是程序入口点的代码片段。
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.create_task(amain(loop=loop))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
Run Code Online (Sandbox Code Playgroud)
当我运行该程序时,我收到以下警告:
server.py:61: DeprecationWarning: There is no current event loop
loop = asyncio.get_event_loop()
Run Code Online (Sandbox Code Playgroud)
实现这个的正确方法是什么?
我正在使用asyncioPython 3.5中的使用流程,但我还没有看到我应该做什么await以及我不应该做的事情或者可以忽略不计的事情的描述.我是否必须在"这是一个IO操作,因此应该await编辑" 方面使用我的最佳判断?
我想找到简单的异步服务器示例.我有很多等待,数据库事务等功能:等等:
def blocking_task(n):
for i in xrange(n):
print i
sleep(1)
return i
Run Code Online (Sandbox Code Playgroud)
我需要在没有阻塞的情况下在分离的进程中运行它 可能吗?
如何正确利用 FastAPI 路由中的异步功能?
以下代码片段需要 10 秒才能完成对我的/home路由的调用,而我预计只需要 5 秒。
from fastapi import FastAPI
import time
app = FastAPI()
async def my_func_1():
"""
my func 1
"""
print('Func1 started..!!')
time.sleep(5)
print('Func1 ended..!!')
return 'a..!!'
async def my_func_2():
"""
my func 2
"""
print('Func2 started..!!')
time.sleep(5)
print('Func2 ended..!!')
return 'b..!!'
@app.get("/home")
async def root():
"""
my home route
"""
start = time.time()
a = await my_func_1()
b = await my_func_2()
end = time.time()
print('It took {} seconds to finish execution.'.format(round(end-start)))
return …Run Code Online (Sandbox Code Playgroud) 我对在 Python 中创建 Web 服务相当陌生。我已经成功创建了一个 Flask Web 服务并使用 Gunicorn 运行它(因为 Flask 的内置服务器不适合生产)。这就是我运行我的应用程序的方式(有 4 个工作节点)。
gunicorn --bind 0.0.0.0:5000 My_Web_Service:app -w 4
Run Code Online (Sandbox Code Playgroud)
问题是,这一次只能处理 4 个请求。我希望它能够同时处理 1000 个潜在的请求。我应该使用多线程吗?还有其他选择/建议吗?
假设我需要请求多个服务器做出响应
def view_or_viewset(request):
d1 = request_a_server() # something like requests.get(url, data)
d2 = request_b_server()
d3 = request_c_server()
d4 = do_something_with(d3)
return Response({"foo1": d1, "foo2": d2, "foo3": d3, "foo4": d4})
Run Code Online (Sandbox Code Playgroud)
我正在为每个请求执行同步请求,我想一定有更好的方法来处理这种情况。
(如果任务很长,我会使用 celery,但事实并非如此,仍然执行多个同步请求似乎不对)
处理这个问题的推荐范例(?)是什么?
我期待使用asyncor aioHttpand yield(?)
我的问题被标记为可能重复,并且那里的答案建议使用线程..我认为手动处理线程是应该避免的(根据我过去在 c++ 中使用多线程的经验)
然后我发现/sf/answers/1673142411/ request-future 在这里似乎很有希望..
python ×7
asynchronous ×2
python-3.5 ×2
aiosmtpd ×1
django ×1
fastapi ×1
flask ×1
gunicorn ×1
tornado ×1