2012-02-17 54 views
1

我有很長的編程背景,但是對Python來說是新手,並且正在與Tornado一起玩,爲某個長輪詢服務創建原型。如何在數據可用時完成Tornado長輪詢請求

我想要實現的是用戶連接到說example.com/get/1234,這是長期民意調查的一部分。 1234是用戶標識。目前,它只是掛起並等待內容。然後,用戶使用新標籤頁/其他瀏覽器/其他計算機/等,並轉到url,如example.com/set/1234?data=abcd,其中1234是用戶標識,數據是內容爲「abcd」的變量。現在,當發生這種情況時,第一個獲取請求應該打印出數據「abcd」並完成請求。用戶標識顯然用於允許多個用戶同時使用該服務。所以,簡單地說:

1)進入example.com/get/1234 - >等待 2)在另一個選項卡,打開example.com/set/1234?data=abcd 3)此請求後,右,第一請求打印出abcd並完成

下面是我一直在嘗試的東西,但我並沒有真正推進,也找不到適當的Google關鍵字來解決這個問題。

class GetHandler(tornado.web.RequestHandler): 
    @tornado.web.asynchronous 

    # Getting user ID is working 
    def get(self, user_id): 

     # This is something I'm not sure is right, but found it in an 
     # example. I haven't created the code_received function yet, 
     # nor know if it should be here? Should the code_received 
     # and connection finishing be called from the /set part? 

     cursor = self.get_argument("cursor", None) 
     self.wait_for_code(self.code_received, cursor=cursor) 

    def code_received(self, data) 
     self.write(data) 
     self.finish() 

所有幫助非常感謝。提前致謝!

回答

1

我實際上設法解決了這個問題,發現了solution

只是爲了以防別人概括爲尋找到這一點:我救了聽衆的字典與user_id/set叫,我傳遞消息監聽器具有相同user_id。如果有人有興趣,我可以分享更多的代碼。

1

簡單的解決方法是添加一個超時回調

class GetHandler(tornado.web.RequestHandler): 

    @tornado.web.asynchronous 
    def get(self, user_id):  

     def check(): 
      # here you must implement something to discover if the result exists 
      # for example, you can keep a dictionary with id : result 
      # so initially 1234 : None 
      # after setting 1234 : someVal (this happens from the SetHandler) 
      # then if below succeeds 
      if there_is_a_result: 
       self.write(result) 
       self.finish() 
      else: # result not ready, add another timeout callback 
       tornado.ioloop.IOLoop.instance().add_timeout(datetime.timedelta(0.00001), check) 

     tornado.ioloop.IOLoop.instance().add_timeout(datetime.timedelta(0.00001), check) 

編輯:一個更好的解決辦法是使用WebSockets + Redis的+發佈訂閱。我自己沒有用過這個,但是有一個例子here

+0

謝謝你回答@hymloth!但是這個解決方案基本上會循環並不斷執行比較代碼 - 當用戶數量增長時,這不會導致性能問題嗎?如果是這樣,有沒有辦法在等待數據輸入的同時「掛起」請求? – MonkeyPetteri 2012-02-17 17:26:57

+0

感謝您的更新@hymloth - 我正在考慮它,但似乎Firefox 3.x不支持websockets ..這是一個要求。任何其他想法? – MonkeyPetteri 2012-02-18 17:44:52

相關問題