Skip to content

Instantly share code, notes, and snippets.

@ejucovy
Created October 16, 2013 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ejucovy/7007820 to your computer and use it in GitHub Desktop.
Save ejucovy/7007820 to your computer and use it in GitHub Desktop.
Trac WSGI script that sets database uri from environment variable
import os
import trac.web.main
from trac.env import open_environment, Environment
from trac.util import translation
import gc
import threading
def application(environ, start_response):
req = trac.web.main.RequestWithSession(environ, start_response)
run_once = environ['wsgi.run_once']
env = env_error = None
try:
env = Environment(os.environ['TRAC_ENV'])
if env.base_url_for_redirect:
environ['trac.base_url'] = env.base_url
# Web front-end type and version information
if not hasattr(env, 'webfrontend'):
mod_wsgi_version = environ.get('mod_wsgi.version')
if mod_wsgi_version:
mod_wsgi_version = (
"%s (WSGIProcessGroup %s WSGIApplicationGroup %s)" %
('.'.join([str(x) for x in mod_wsgi_version]),
environ.get('mod_wsgi.process_group'),
environ.get('mod_wsgi.application_group') or
'%{GLOBAL}'))
environ.update({
'trac.web.frontend': 'mod_wsgi',
'trac.web.version': mod_wsgi_version})
env.webfrontend = environ.get('trac.web.frontend')
if env.webfrontend:
env.systeminfo.append((env.webfrontend,
environ['trac.web.version']))
except Exception, e:
env_error = e
print "Persistent database setting is %s" % env.config.get("trac", "database")
if 'TRAC_DATABASE' in os.environ:
env.config.set("trac", "database", os.environ['TRAC_DATABASE'])
print "Overriding persistent database setting with %s" % env.config.get("trac", "database")
translation.make_activable(lambda: req.locale, env.path if env else None)
try:
return trac.web.main._dispatch_request(req, env, env_error)
finally:
translation.deactivate()
if env and not run_once:
env.shutdown(threading._get_ident())
unreachable = gc.collect()
@ejucovy
Copy link
Author

ejucovy commented Oct 16, 2013

I had to instantiate an Environment() directly instead of using open_environment() because the latter sets up a database connection in order to check if the environment needs to be upgraded .. so then it doesn't have any effect if I change the database config value after the connection has been opened.

But, this way the site will probably fail to check setup participants' environment_needs_upgrade functions .. so that probably needs to be added back in somewhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment