2016-07-27 76 views
0

我想從燒瓶部分發送會話數據到我的應用程序的Websocket部分。一個簡單的例子是:燒瓶到高速公路並扭曲:RuntimeError:在請求範圍外工作

from flask import session 

class EchoServerProtocol(WebSocketServerProtocol): 
    def __init__(self): 
     self.user= session.get('user') 

    def onMessage(self, payload, isBinary): 
     _user=self.user 

     self.sendMessage(payload, isBinary, _user) 

app = Flask(__name__) 

app.secret_key = str(uuid.uuid4()) 

@app.route('/') 
def page_home(): 
    return render_template('index.html') 

(改編自here)。

我接收到的錯誤:

File "app.py", line 171, in __init__ 
    if session.get('user'): 
    File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 338, in __getattr__ 
    return getattr(self._get_current_object(), name) 
    File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 297, in _get_current_object 
    return self.__local() 
    File "/usr/local/lib/python2.7/dist-packages/flask/globals.py", line 20, in _lookup_req_object 
    raise RuntimeError('working outside of request context') 
exceptions.RuntimeError: working outside of request context 
+0

我對Autobahn並不熟悉,但Flask'session'對象有點神奇,只有在* Flask *處理請求時(或Flask請求上下文處於活動狀態時)纔可用。在您鏈接的代碼中,Autobahn正在處理與處理常規請求的Flask分開的Web套接字。你可以嘗試使用Flask-Socket或Flask-SocketIO來使Flask知道web套接字。 – matts

+0

在發佈的例子中,EchoServerProtocol是通過index.html實現的,所以它不是完全分開的 – Mostafa

+0

渲染'index.html'的結果是在客戶端執行,而不是在服務器端的請求上下文中執行。 – davidism

回答

0

臨時解決方案,我發現是用戶名保存爲將燒瓶部分泡菜對象,並加載泡菜對象在網頁套接字部分,如:

from flask import session 
import pickle 

class EchoServerProtocol(WebSocketServerProtocol): 
    def __init__(self): 
     self.user= pickle.load(open('../static/uploads/userfile.p', 'rb')) 

    def onMessage(self, payload, isBinary): 
     _user=self.user 

     self.sendMessage(payload, isBinary, _user) 

app = Flask(__name__) 

app.secret_key = str(uuid.uuid4()) 

@app.route('/') 
def page_home(): 
    _user=session.get('user') 

    pickle.dump(_user, open('../static/uploads/userfile.p', 'wb')) 

    return render_template('index.html') 
+0

Yikes!這種方法的性能損失是多少? –

+0

我不知道,我主要擔心這種方法不會擴展到許多用戶的服務器。我爲每個人使用單個文件'userfile.p',希望2個不同的用戶不會同時訪問同一個文件。 – Mostafa

+0

你有沒有考慮過克萊因或龍捲風?使用Klein可以非常方便地使用Autobahn,而Tornado也有一個簡單的網絡套接字模塊。正如你所知道的,Flask在幕後做了很多魔術,這使得有時難以編程,Websockets成爲了這些困難的領域之一。 –