title: how to setup sqlalchemy session in celery tasks with no global variable
body: <p>Summary: I want to use a sqlalchemy session in celery tasks without having a global variable containing that session.</p>
  
  <p>I am using SQLAlchemy in a project with celery tasks, and I'm having </p>
  
  <p>Currently, I have a global variable 'session' defined along with my celery app setup (celery.py), with a worker signal to set it up.</p>
  
  <pre><code>session = scoped_session(sessionmaker())
  
  @celeryd_init.connect
  def configure_workers(sender=None, conf=None, **kwargs):
      # load the application configuration
      # db_uri = conf['db_uri']
      engine = create_engine(db_uri)
      session.configure(bind=engine)
  </code></pre>
  
  <p>In the module defining the tasks, I simply import 'session' and use it. Tasks are defined with a custom class that closes the session after returning:</p>
  
  <pre><code>class DBTask(Task):
      def after_return(self, *args, **kwargs):
          session.remove()
  </code></pre>
  
  <p>That works well, however: when unit testing with CELERY_ALWAYS_EAGER=True, the session won't be configured. The only solution I've found so far is to mock that 'session' variable when running a task in a unit test:</p>
  
  <pre><code>with mock.patch('celerymodule.tasks.session', self.session):
      do_something.delay(...)
  </code></pre>
  
  <p>While it works, I don't want to do that.</p>
  
  <p>Is there any way to setup a session that will no be a global variable, that will work both for normal asynchronous behavior and without workers with CELERY_ALWAYS_EAGER=True?</p>