2016-12-30 91 views
0
  • 您好我正在使用Klein我的web服務器的Python模塊。
  • 我需要分別運行每個請求作爲一個線程,還需要 返回結果。
  • 但克萊因等待完成單個請求以處理 另一個請求。
  • 我也嘗試從扭曲模塊使用deferToThread。但它也 只處理完第一個請求後的請求。
  • 同樣我也試過@inlineCallbacks方法它也產生 相同的結果。

注意:當沒有任何東西可以返回時,這種方法可以很好地工作。 但我需要返回結果。同時處理多個請求並使用Klein模塊Python返回結果

在這裏,我附低於示例代碼段,

import time 
import klein 
import requests 
from twisted.internet import threads 

def test(): 
    print "started" 
    x = requests.get("http://google.com") 
    time.sleep(10) 
    return x.text 

app = klein.Klein() 

@app.route('/square/submit',methods = ['GET']) 
def square_submit(request): 
    return threads.deferToThread(test) 

app.run('localhost', 8000) 
+0

Twisted應該能夠並行運行多個請求。起初使用有點棘手。也許你可以提供你的扭曲的代碼,讓我們看看它。否則,我會研究'multiprocessing'和/或'multithreading'模塊。我可能會使用一個隊列來處理返回值的通信。看看這個'queue'模塊。 –

+0

@TammoHeeren感謝您的回覆。你能否提一下使用隊列模塊的參考鏈接? –

回答

0

但是克萊因等待,直到單個請求來處理另一個請求的完成。

這是不正確的。事實上,你提供的代碼絕對沒有錯。只需在tcp:localhost:8000運行您的示例服務器,並使用以下命令curl,無效的要求:

curl http://localhost:8000/square/submit & # run in background 
curl http://localhost:8000/square/submit 

上午我假設你在Web瀏覽器中測試代碼是否正確?如果你是,那麼你正在經歷大多數現代瀏覽器的「功能」。瀏覽器將在給定時間對每個URL發出一次請求。圍繞這個瀏覽器的一個方法是在URL的末尾添加一個虛假的查詢字符串,像這樣:

http://localhost:8000/squre/submit 
http://localhost:8000/squre/submit?bogus=0 
http://localhost:8000/squre/submit?bogus=1 
http://localhost:8000/squre/submit?bogus=2 

然而,一個非常常見的錯誤新的扭曲/克萊因開發商往往使是寫阻塞代碼,認爲Twisted會神奇地使它異步。例如:

@app.route('/square/submit') 
def square_submit(): 
    print("started") 
    x = requests.get('https://google.com') # blocks the reactor 
    time.sleep(5) # blocks the reactor 
    return x.text 

這樣的代碼將按順序處理請求,並應該使用異步替代方法進行修改。

+0

感謝您的回覆。我會尋找一些異步的替代品。 –

+0

你可以用'''treq''](https://treq.readthedocs.io/en/latest/)替換''request'',你可以像''task.deferLater()''或''task.deferLater 'reactor.callLater()''模仿''time.sleep''。 –