I have been developing an app using Flask, Python and Flask-Socket.io library. The problem I have is that the following code will not perform an emit
correctly due to some contexts issue
RuntimeError: working outside of request context
I am writing only one python file for the entire program by now. This is my code (test.py):
from threading import Thread
from flask import Flask, render_template, session, request, jsonify, current_app, copy_current_request_context
from flask.ext.socketio import *
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
def somefunction():
# some tasks
someotherfunction()
def someotherfunction():
# some other tasks
emit('anEvent', jsondata, namespace='/test') # here occurs the error
@socketio.on('connect', namespace='/test')
def setupconnect():
global someThread
someThread = Thread(target=somefunction)
someThread.daemon = True
if __name__ == '__main__':
socketio.run(app)
Here in StackExchange I have been reading some solutions, but they didn't work. I do not know what I am doing wrong.
I have tried adding a with app.app_context():
before my emit
:
def someotherfunction():
# some other tasks
with app.app_context():
emit('anEvent', jsondata, namespace='/test') # same error here
Another solution I tried is adding the decorator copy_current_request_context
before someotherfunction()
but it says that the decorator must be in a local scope. I put it in inside someotherfunction()
, first line, but same error.
I would be glad if someone can help me with this. Thanks in advance.