我正在尝试从侦听器中访问 current_app,以便我可以使用应用程序配置值来订阅哪个频道。但是我收到“RuntimeError:在应用程序上下文之外工作”。
这是有问题的代码:
from flask import Blueprint, Response, request, current_app
from socketio import socketio_manage
from socketio.namespace import BaseNamespace
from redis import StrictRedis
import pprint
socketapp = Blueprint('socketapp', __name__)
class MessageNamespace(BaseNamespace):
def listener(self):
pprint.pprint(current_app.config)
r = StrictRedis()
p = r.pubsub()
p.subscribe('message-channel')
messages = r.lrange('message', 0, -1)
self.emit('message-message', ''.join(messages))
for m in p.listen():
if m['type'] == 'message':
self.emit('message-message', m['data'])
def on_subscribe(self):
self.spawn(self.listener)
@socketapp.route('/socket.io/<path:remaining>')
def socketio(remaining):
try:
socketio_manage(request.environ, {'/messages': MessageNamespace}, request)
except BaseException:
pass
return Response()
@socketapp.route('/message', methods=['GET'])
def say():
msg = request.args.get('msg', None)
if msg:
r = StrictRedis(host=current_app.config['REDIS_HOST'])
r.rpush('message', msg)
r.publish('message-channel', msg)
return Response('Message sent!')
else:
return Response('Please specify your message in the "msg" parameter')