title: Flask - Not bounded to current context
body: <p>I am trying to write a class, ChangeBackStatusOnErrorTask which does exactly as its name implies.</p>
  
  <pre><code>class ChangeBackStatusOnErrorTask(Task):
    abstract = True
  
    def on_failure(self, exc, task_id, args, kwargs, einfo):
      server = Server.query.get(server_id)
      server.status = RemoteStatus.ERROR
      db.session.commit()
  
  
  @celery.task(bind=True, base=ChangeBackStatusOnErrorTask)
  def deploy_server(self, server_id):
    try:
      server.status = RemoteStatus.LAUNCHING
      db.session.commit()
  
      host = server.ssh_user + '@' + server.ip
      execute(fabric_deploy_server, self, server, hosts=host)
  
      server.status = RemoteStatus.LAUNCHED
      db.session.commit()
    except Exception as e:
      server.status = RemoteStatus.ERROR
      db.session.commit()
      traceback.print_exc()
      raise e
  </code></pre>
  
  <p>However, this code is not working due to the fact that ChangeBackStatusOnErrorTask is not bounded to my Flask context: </p>
  
  <pre><code>  File "/Users/vng/.virtualenvs/AutomataHeroku/lib/python2.7/site-packages/celery/app/trace.py", line 367, in trace_task
      R = retval = fun(*args, **kwargs)
    File "/Users/vng/.virtualenvs/AutomataHeroku/lib/python2.7/site-packages/celery/app/trace.py", line 622, in __protected_call__
      return self.run(*args, **kwargs)
    File "/Users/vng/Dropbox/Code/Affiliate/AutomataHeroku/automata/server/tasks.py", line 59, in deploy_server
      server = Server.query.get(server_id)
    File "/Users/vng/.virtualenvs/AutomataHeroku/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 498, in __get__
      return type.query_class(mapper, session=self.sa.session())
    File "/Users/vng/.virtualenvs/AutomataHeroku/lib/python2.7/site-packages/sqlalchemy/orm/scoping.py", line 78, in __call__
      return self.registry()
    File "/Users/vng/.virtualenvs/AutomataHeroku/lib/python2.7/site-packages/sqlalchemy/util/_collections.py", line 990, in __call__
      return self.registry.setdefault(key, self.createfunc())
    File "/Users/vng/.virtualenvs/AutomataHeroku/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 2861, in __call__
      return self.class_(**local_kw)
    File "/Users/vng/.virtualenvs/AutomataHeroku/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 143, in __init__
      self.app = app = db.get_app()
    File "/Users/vng/.virtualenvs/AutomataHeroku/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 957, in get_app
      'application not registered on db instance and no application'
  RuntimeError: application not registered on db instance and no application bound to current context
  </code></pre>
  
  <h1>How can I fix this?</h1>