title: Flask, Python and Socket.io: multithreading app is giving me "RuntimeError: working outside of request context"
body: <p>I have been developing an app using <strong>Flask</strong>, <strong>Python</strong> and <strong>Flask-Socket.io</strong> library. The problem I have is that the following code will not perform an <code>emit</code> correctly due to some contexts issue </p>
  
  <pre><code>RuntimeError: working outside of request context
  </code></pre>
  
  <p>I am writing only one python file for the entire program by now. This is my code (<strong>test.py</strong>):</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>Here in StackExchange I have been reading some solutions, but they didn't work. I do not know what I am doing wrong.</p>
  
  <p>I have tried adding a <code>with app.app_context():</code> before my <code>emit</code>:</p>
  
  <pre><code>def someotherfunction():
      # some other tasks
      with app.app_context():
          emit('anEvent', jsondata, namespace='/test') # same error here
  </code></pre>
  
  <p>Another solution I tried is adding the decorator <code>copy_current_request_context</code> before <code>someotherfunction()</code> but it says that the decorator must be in a local scope. I put it in inside <code>someotherfunction()</code>, first line, but same error.</p>
  
  <p>I would be glad if someone can help me with this. Thanks in advance.</p>