要使代碼異步,您需要使用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 –