我正在寫一個小應用程序,我使用Tornado websockets。我使用Cookie進行身份驗證,因此我想在建立Web套接字時檢查這一點。如何強制Tornado websockets在握手時產生錯誤頁面
因此,這裏的挑戰(官方的WebSockets例如建築):
class EchoWebSocket(tornado.websocket.WebSocketHandler):
def open(self):
userx = self.get_secure_cookie("user")
if not userx:
self.send_error(403) #I want to redirect or otherwise stop the user
print "WebSocket opened"
def on_message(self, message):
userx = self.get_secure_cookie("user")
self.write_message(u"%s said: %s" % (userx, message))
def on_close(self):
print "WebSocket closed"
事實證明,這是不是很流行的旋風,引發此錯誤:
ERROR:root:Exception in callback <tornado.stack_context._StackContextWrapper object at 0x10fa10db8>
Traceback (most recent call last):
....
File "/Library/Python/2.7/site-packages/tornado-2.4-py2.7.egg/tornado/iostream.py", line 565, in _check_closed
raise IOError("Stream is closed")
IOError: Stream is closed
它甚至可能在websockets握手期間「驗證或取消」?這是我的代碼的問題,還是與Tornado有問題/缺少功能?在這種情況下,Tornado是否能夠通過websocket發送一些錯誤條件來觸發客戶端的onerror處理程序(在手冊中找不到任何強制錯誤條件的方式)?
我想實現的事件順序是:
在使用常規的Web請求的用戶日誌和會話令牌被存儲爲安全cookie
用戶加載頁面使用websockets,javascript嘗試建立套接字
在套接字建立之前我想檢查是否存在有效會話標記
- 如果有效令牌,套接字被建立和我的應用程序按預期工作
- 如果無效標誌,沒有插座,用戶將收到錯誤(或者,一個WebSocket的錯誤情況是由服務器提出)
在websockets握手期間甚至可以「驗證或取消」嗎? - 是的,但不是這樣。發送消息給用戶並關閉連接。 –
夠公平的。應該很容易實現我的猜測。 – agnsaft