[英]How a python function called and do not wait it finish processing meanwhile that function must be called once. So, thread must be stop
I am using a script that handle ws requests and response them as json. 我正在使用处理ws请求并将其作为json响应的脚本。 How ever at the same time those information must be insert/update to DB.
必须同时将这些信息插入/更新到DB。 But i don t want to wait DB.
但是我不想等待DB。 I should return the response asap.
我应该尽快返回响应。 I am using "bottle" in python to do so.
我在python中使用“瓶”来做。 How can i reach the solution.
我如何才能找到解决方案。
I found the answer asyncio. 我找到了答案异步。 However its working on python3.
但是它在python3上工作。 This is the site that i reach.
这是我到达的站点。 They have good explantation there.
他们在那里有很好的移栽。 https://medium.freecodecamp.org/a-guide-to-asynchronous-programming-in-python-with-asyncio-232e2afa44f6
https://medium.freecodecamp.org/a-guide-to-asynchronous-programming-in-python-with-asyncio-232e2afa44f6
An this is an example from thier resources. 这是他们资源中的一个例子。
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.