Skip to content

Instantly share code, notes, and snippets.

@UtahDave
Forked from fatbox/djangomodule.py
Created January 28, 2012 14:35
Show Gist options
  • Save UtahDave/1694534 to your computer and use it in GitHub Desktop.
Save UtahDave/1694534 to your computer and use it in GitHub Desktop.
Load Django modules from within a Salt module
"""
This allows you to import Django modules into a Salt module
"""
import logging
import sys
import os
log = logging.getLogger(__name__)
# point this at the virtualenv dir that your django deployment runs out of
# you are using virtualenv. right?
DJANGO_ENV = '/home/core/python-envs/production'
# where your code lives (ie where settings.py is)
DJANGO_DIR = '/home/core/code/production'
log.debug("Preapring Django modules...")
# save a reference to our path
# we'll use this to move our new items to the front
prev_sys_path = list(sys.path)
# put the main Django directory on first
sys.path.append(DJANGO_DIR)
# then the virtualenv dir
import site
site_packages = os.path.join(DJANGO_ENV, 'lib', 'python%s' % sys.version[:3], 'site-packages')
site.addsitedir(site_packages)
# Move the added items to the front of the path:
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
# setup the Django environment pointing to our settings
import settings
import django.core.management
django.core.management.setup_environ(settings)
# finally, import our objects
from yourapp.models import YourModel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment