# --- django.wsgi - in any project
from some_common_module import wsgi_helper
application = wsgi_helper.setup(__file__)


# --- wsgi_helper.py - in some_common_module
import os, sys
import django.core.handlers.wsgi

def setup(filename):
	project_root = os.sep.join(filename.split(os.sep)[:-2])
	project_dir = None
	
	for path in os.listdir(project_root):
		# Find each dir off the root, and check it for settings.py
	
		path = os.path.join(project_root, path)
	
		if os.path.isdir(path):
			file = "".join([path, os.sep, "settings.py"])
			if os.path.exists(file):
				# We have found /project_name/settings.py
				project_dir = path
				os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % path.split(os.sep)[-1]
	
	if not project_dir:
		raise Exception("Could not find project settings file! Checked path: %s" % path)
	
	if project_root not in sys.path: sys.path.insert(0, project_root)
	if project_dir not in sys.path: sys.path.insert(0, project_dir)

	return django.core.handlers.wsgi.WSGIHandler()