简体   繁体   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

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.

相关问题 Python:如何等到 function 在不同的线程中被调用? - Python: How to wait until a function has been called in a different thread? Mocking 一个 function 返回一个 object 导致 AssertionError: Expected '...' to have been called 一次。 调用 0 次 - Mocking a function returning an object results in AssertionError: Expected '...' to have been called once. Called 0 times 如何不等功能完成python - How to not wait for function to finish python 如何在tkinter中验证按钮,以便该函数仅被调用一次? - How do I validate a button in tkinter so that the function is only called once? 等待函数完成python - Wait for function to finish python 如何在python中运行该线程外部的线程中调用的函数 - how to run a function called in a thread outside that thread in python Python线程:等待线程停止然后执行函数 - Python threading: wait for thread to stop then execute function Python如何分辨“这被称为函数”? - How do Python tell “this is called as a function”? 如何在python / tkinter中只允许每分钟调用一次函数? - How to allow a function to only be called once a minute in python / tkinter? 如何在函数外部访问函数内部产生的字典,而又不需多次调用函数。 蟒蛇 - How to access a dictionary produced within a function, outside the function, without calling the function more than once. PYTHON
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM