Skip to content

Instantly share code, notes, and snippets.

@radiosilence
Created June 21, 2013 20:53
Show Gist options
  • Save radiosilence/5834254 to your computer and use it in GitHub Desktop.
Save radiosilence/5834254 to your computer and use it in GitHub Desktop.
try:
import threading
currentThread = threading.currentThread
except ImportError:
def currentThread():
return "no threading"
_sites = {}
def set_site(site):
from django.db import connections
try:
dbdetails = DBDetails.objects.get(site=site)
alias = dbdetails.slug
db = {
'ENGINE': dbdetails.database_engine,
'HOST': dbdetails.database_host,
'NAME': dbdetails.database_name,
'USER': dbdetails.database_user,
'PORT': dbdetails.database_port,
'PASSWORD': dbdetails.database_password,
'OPTIONS': json.loads(dbdetails.database_options),
}
backend = load_backend(db['ENGINE'])
conn = backend.DatabaseWrapper(db, alias)
connections['default'] = conn
_sites[currentThread()] = site
except Exception as e:
raise Exception('There was an issue loading database configuration for this site.')
def get_site():
return _sites.get(currentThread(),None)
class CurrentDomainMiddleware:
def process_request(self, request):
# Set up the Site model meta option db_table as explained here -
# http://stackoverflow.com/questions/1160598/how-to-use-schemas-in-django
# This will make sure that queries on this model will always go to the master schema
domain = request.get_host()
# print domain
# print [(site.domain, site.database_name) for site in Site.objects.all()]
try:
site = Site.objects.get(domain=domain)
set_site(site)
except Site.DoesNotExist:
pass
return None
def process_response(self, request, response):
_sites.pop(currentThread(), None)
return response
def process_exception(self, request, exception):
_sites.pop(currentThread(), None)
return exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment