title: Accessing to application context in flask socketio background task
body: <p>I am developing a <strong>Flask</strong> application with <strong>Flask-SocketIO</strong> library to real time communication between a server background task and clients.</p>
  
  <p>I need to access to my database inside the background task and I don't know how to achieve it as no application context is initialized.</p>
  
  <p>My code is:</p>
  
  <pre><code>@socketio.on('connect', namespace='/rt/notifications/')
  def start_notifications_thread():
      global thread
      with thread_lock:
          if thread is None:
              thread = socketio.start_background_task(target=notifications_job)
  
  def notifications_job():
      last_alert_id = None
      while True:
          socketio.sleep(60)
          last_id = Alert.get_last_alert_id()  # Flask-SQLAlchemy model
          if last_alert_id is not None and last_id != last_alert_id:
              socketio.emit('new_alerts', {'msg': 'New alert', 'id': last_id}, namespace='/rt/notifications/')
          last_alert_id = last_id
  </code></pre>