要使代码异步,您需要使用Twisted Deferreds作为described here。延迟为您提供异步代码执行的API,它们允许您将回调附加到您的函数,并在由reactor对象管理的Twisted事件循环中执行代码。
我看到两种可能的方式来使用延迟你的情况。
1)在后台执行的任务与reactor.callLater()
这是确定的,如果dostuff
处理程序不关心结果。您可以使用reactor.callLater()。这样您的异步函数将在您从doStuff
返回值后执行。
因此,像这样:
from klein import run, route, Klein
from twisted.internet import defer, task, reactor
import os
app = Klein()
def logging(data):
ofile = open("file", "w")
ofile.write(data)
result = os.system("ls")
print(result)
@route('/')
def dostuff(request):
reactor.callLater(0, logging, "some data")
print("check!")
return b'Hello, world!'
run("localhost", 8080)
与此代码的事件顺序如下,第一个“检查”被打印出来,然后在“Hello World”的响应返回,并最终异步调用suceeds并打印运行结果为os.system()
。
2016-08-11 08:52:33+0200 [-] check!
2016-08-11 08:52:33+0200 [-] "127.0.0.1" - - [11/Aug/2016:06:52:32 +0000] "GET/HTTP/1.1" 200 13 "-" "curl/7.35.0"
a.py file
2)在后台执行任务,并与task.deferLater()
得到的结果,如果你关心你的“记录”功能的结果,你还可以将回调到该对象和使用twisted.internet.task API。如果你想要走这条路,你需要重构自己的处理程序是这样
@route('/')
def dostuff(request):
def the_end(result):
print("executed at the end with result: {}".format(result))
dfd = task.deferLater(reactor, 0, logging, "some data")
dfd.addCallback(the_end)
print("check!")
return b'Hello, world!'
工作这一事件的方式订货会和上面一样,但the_end
功能将在年底后您的logging
函数完成执行。
2016-08-11 08:59:24+0200 [-] check!
2016-08-11 08:59:24+0200 [-] "127.0.0.1" - - [11/Aug/2016:06:59:23 +0000] "GET/HTTP/1.1" 200 13 "-" "curl/7.35.0"
a.py file
2016-08-11 08:59:24+0200 [-] executed at the end with result: some result
因为我对扭曲的Klein的知识主要来自http://tavendo.com/blog/post/going-asynchronous-from-flask-to-twisted-klein/您的回答非常有帮助。我还没有尝试,但我会认为它是正确的。非常感谢你。真的很感激它。 – JLTChiu
作为一个更新,代码工作,但我的pyCharm和pylint显示错误'E:512,4:模块'twisted.internet.reactor'没有'callLater'成员(无成员)'但问题是这个代码似乎完全好(它按预期工作)。有没有办法来解决这个问题? – JLTChiu
看起来更像是pycharm代码检查中的一些错误,可能是平台特定的东西?在做这种检查时,你必须检查pycharm的外观,以及为什么这个代码会失败。我自己使用pycharm,我不太相信它的风格警告,其中许多是虚惊一场。 flake8是检查python代码风格的更好工具IMO –