【发布时间】:2019-05-13 06:34:18
【问题描述】:
我想知道,web.py服务响应后是否可以运行一个函数,哪个函数需要很长时间才能运行?
下面举个例子。
文件名:code.py
import web
import time
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
try:
with open('filename.txt', 'a') as file:
for i in range(100):
time.sleep(1)
file.write("No of times: {}".format(i))
return "some json response"
except:
return "Exception occurred"
if __name__ == "__main__":
app.run()
当我运行上面的代码时,显然这需要时间,因为我们使用时间模块休眠一秒然后写入文件。所以,我应该等待 100 秒才能得到服务的响应。
我想跳过这 100 秒的等待时间。
预期:先向客户端返回响应,然后在后台运行这部分?
谁能提供一些解决方案。谢谢..
【问题讨论】:
-
使用 python
threading模块。让文件在单独的线程中保存工作,您当前的线程将正常返回响应。 -
在后台发送文件写入将意味着您将无法
return "Exception occurred"可以吗?