我想将会话数据从Flask部分发送到我的应用程序的Websocket部分。一个简单的例子是:
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 :(得分:0)
我找到的临时解决方案是将用户名保存为Flask部分中的pickle对象,并在websocket部分中加载pickle对象,如:
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')