繁体   English   中英

python函数如何调用而不等待它完成处理,而该函数必须被调用一次。 因此,线程必须停止

[英]How a python function called and do not wait it finish processing meanwhile that function must be called once. So, thread must be stop

我正在使用处理ws请求并将其作为json响应的脚本。 必须同时将这些信息插入/更新到DB。 但是我不想等待DB。 我应该尽快返回响应。 我在python中使用“瓶”来做。 我如何才能找到解决方案。

我找到了答案异步。 但是它在python3上工作。 这是我到达的站点。 他们在那里有很好的移栽。 https://medium.freecodecamp.org/a-guide-to-asynchronous-programming-in-python-with-asyncio-232e2afa44f6

这是他们资源中的一个例子。

import asyncio  
import time  
from datetime import datetime

async def custom_sleep():  
    print('SLEEP', datetime.now())
    time.sleep(1)
async def factorial(name, number):  
    f = 1
    for i in range(2, number+1):
        print('Task {}: Compute factorial({})'.format(name, i))
        await custom_sleep()
        f *= i
    print('Task {}: factorial({}) is {}\n'.format(name, number, f))

start = time.time()  
loop = asyncio.get_event_loop()
tasks = [  
    asyncio.ensure_future(factorial("A", 3)),
    asyncio.ensure_future(factorial("B", 4)),
]
loop.run_until_complete(asyncio.wait(tasks))  
loop.close()
end = time.time()  
print("Total time: {}".format(end - start))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM