Colin Copeland avatar Colin Copeland committed 4efec99

add example-django-project

Comments (0)

Files changed (17)

Add a comment to this file

example-django-project/caktus_website/__init__.py

Empty file added.

example-django-project/caktus_website/apache/staging.conf

+<VirtualHost *:80>
+    WSGIScriptReloading On
+    WSGIReloadMechanism Process
+    WSGIDaemonProcess caktus_website-staging
+    WSGIProcessGroup caktus_website-staging
+    WSGIApplicationGroup caktus_website-staging
+    WSGIPassAuthorization On
+    
+    WSGIScriptAlias / /home/caktus/www/staging/caktus_website/apache/staging.wsgi/
+    
+    <Location "/">
+        Order Allow,Deny
+        Allow from all
+    </Location>
+    
+    <Location "/media">
+        SetHandler None
+    </Location>
+
+    Alias /media /home/caktus/www/staging/caktus_website/media
+    
+    <Location "/admin-media">
+        SetHandler None
+    </Location>
+    
+    Alias /admin-media /home/caktus/www/staging/caktus_website/media/admin
+    
+    ErrorLog /home/caktus/www/log/error.log
+    LogLevel info
+    CustomLog /home/caktus/www/log/access.log combined
+</VirtualHost>

example-django-project/caktus_website/apache/staging.wsgi

+import os
+import sys
+import site
+
+PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
+site_packages = os.path.join(PROJECT_ROOT, 'env/lib/python2.6/site-packages')
+site.addsitedir(os.path.abspath(site_packages))
+sys.path.insert(0, PROJECT_ROOT)
+os.environ['DJANGO_SETTINGS_MODULE'] = 'caktus_website.settings_staging'
+
+import django.core.handlers.wsgi
+application = django.core.handlers.wsgi.WSGIHandler()
Add a comment to this file

example-django-project/caktus_website/blog/__init__.py

Empty file added.

example-django-project/caktus_website/blog/admin.py

+from django.contrib import admin
+
+from caktus_website.blog.models import Post
+
+
+class PostAdmin(admin.ModelAdmin):
+    list_display = ('title', 'date', 'published')
+    list_filter = ('date', 'published')
+
+admin.site.register(Post, PostAdmin)

example-django-project/caktus_website/blog/models.py

+from django.db import models
+
+
+class Post(models.Model):
+    title = models.CharField(max_length=255)
+    date = models.DateTimeField()
+    body = models.TextField()
+    published = models.BooleanField(default=True)
+
+    def __unicode__(self):
+        return self.title

example-django-project/caktus_website/blog/tests.py

+"""
+This file demonstrates two different styles of tests (one doctest and one
+unittest). These will both pass when you run "manage.py test".
+
+Replace these with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.failUnlessEqual(1 + 1, 2)
+
+__test__ = {"doctest": """
+Another way to test that 1 + 1 is equal to 2.
+
+>>> 1 + 1 == 2
+True
+"""}
+

example-django-project/caktus_website/blog/views.py

+# Create your views here.

example-django-project/caktus_website/bootstrap.py

+#!/usr/bin/env python
+# bootstrap.py
+# Bootstrap and setup a virtualenv with the specified requirements.txt
+import os
+import sys
+import shutil
+import subprocess
+from optparse import OptionParser
+
+
+usage = """usage: %prog [options]"""
+parser = OptionParser(usage=usage)
+parser.add_option("-c", "--clear", dest="clear", action="store_true",
+                  help="clear out existing virtualenv")
+
+
+def main():
+    if "VIRTUAL_ENV" not in os.environ:
+        sys.stderr.write("$VIRTUAL_ENV not found.\n\n")
+        parser.print_usage()
+        sys.exit(-1)
+    (options, pos_args) = parser.parse_args()
+    virtualenv = os.environ["VIRTUAL_ENV"]
+    if options.clear:
+        subprocess.call(["virtualenv", "--clear", "--distribute", virtualenv])
+    file_path = os.path.dirname(__file__)
+    subprocess.call(["pip", "install", "-E", virtualenv, "--requirement",
+                     os.path.join(file_path, "requirements/apps.txt")])
+
+
+if __name__ == "__main__":
+    main()
+    sys.exit(0)
Add a comment to this file

example-django-project/caktus_website/caktus_website.db

Binary file added.

example-django-project/caktus_website/fabfile.py

+import os
+
+from fabric.api import *
+from fabric.contrib.project import rsync_project
+from fabric.contrib import files, console
+from fabric import utils
+from fabric.decorators import hosts
+
+
+RSYNC_EXCLUDE = (
+    '.DS_Store',
+    '.hg',
+    '*.pyc',
+    '*.example',
+    '*.db',
+    'media/admin',
+    'media/attachments',
+    'local_settings.py',
+    'fabfile.py',
+    'bootstrap.py',
+)
+env.home = '/home/caktus/'
+env.project = 'caktus_website'
+
+
+def _setup_path():
+    env.root = os.path.join(env.home, 'www', env.environment)
+    env.code_root = os.path.join(env.root, env.project)
+    env.virtualenv_root = os.path.join(env.root, 'env')
+    env.settings = '%(project)s.settings_%(environment)s' % env
+
+
+def staging():
+    """ use staging environment on remote host"""
+    env.user = 'caktus'
+    env.environment = 'staging'
+    env.hosts = ['173.203.208.254']
+    _setup_path()
+
+
+def production():
+    """ use production environment on remote host"""
+    utils.abort('Production deployment not yet implemented.')
+
+
+def bootstrap():
+    """ initialize remote host environment (virtualenv, deploy, update) """
+    require('root', provided_by=('staging', 'production'))
+    run('mkdir -p %(root)s' % env)
+    run('mkdir -p %s' % os.path.join(env.home, 'www', 'log'))
+    create_virtualenv()
+    deploy()
+    update_requirements()
+
+
+def create_virtualenv():
+    """ setup virtualenv on remote host """
+    require('virtualenv_root', provided_by=('staging', 'production'))
+    args = '--clear --distribute'
+    run('virtualenv %s %s' % (args, env.virtualenv_root))
+
+
+def deploy():
+    """ rsync code to remote host """
+    require('root', provided_by=('staging', 'production'))
+    if env.environment == 'production':
+        if not console.confirm('Are you sure you want to deploy production?',
+                               default=False):
+            utils.abort('Production deployment aborted.')
+    # defaults rsync options:
+    # -pthrvz
+    # -p preserve permissions
+    # -t preserve times
+    # -h output numbers in a human-readable format
+    # -r recurse into directories
+    # -v increase verbosity
+    # -z compress file data during the transfer
+    extra_opts = '--omit-dir-times'
+    rsync_project(
+        env.root,
+        exclude=RSYNC_EXCLUDE,
+        delete=True,
+        extra_opts=extra_opts,
+    )
+    touch()
+
+
+def update_requirements():
+    """ update external dependencies on remote host """
+    require('code_root', provided_by=('staging', 'production'))
+    requirements = os.path.join(env.code_root, 'requirements')
+    with cd(requirements):
+        cmd = ['pip install']
+        cmd += ['-E %(virtualenv_root)s' % env]
+        cmd += ['--requirement %s' % os.path.join(requirements, 'apps.txt')]
+        run(' '.join(cmd))
+
+
+def touch():
+    """ touch wsgi file to trigger reload """
+    require('code_root', provided_by=('staging', 'production'))
+    apache_dir = os.path.join(env.code_root, 'apache')
+    with cd(apache_dir):
+        run('touch %s.wsgi' % env.environment)
+
+
+def bootstrap():
+    """ initialize remote host environment (virtualenv, deploy, update) """
+    require('root', provided_by=('staging', 'production'))
+    run('mkdir -p %(root)s' % env)
+    run('mkdir -p %s' % os.path.join(env.home, 'www', 'log'))
+    create_virtualenv()
+    deploy()
+    update_requirements()
+
+
+def update_apache_conf():
+    """ upload apache configuration to remote host """
+    require('root', provided_by=('staging', 'production'))
+    source = os.path.join('apache', '%(environment)s.conf' % env)
+    dest = os.path.join(env.home, 'apache.conf.d')
+    put(source, dest, mode=0755)
+    apache_reload()
+
+
+def configtest():
+    """ test Apache configuration """
+    run('apache2ctl configtest')
+
+
+def apache_reload():
+    """ reload Apache on remote host """
+    run('sudo /etc/init.d/apache2 reload')
+
+
+def apache_restart():
+    """ restart Apache on remote host """
+    run('sudo /etc/init.d/apache2 restart')
+
+
+def symlink_django():
+    """ create symbolic link so Apache can serve django admin media """
+    admin_media = os.path.join(env.virtualenv_root,
+                               'src/django/django/contrib/admin/media/')
+    media = os.path.join(env.code_root, 'media/admin')
+    if not files.exists(media):
+        run('ln -s %s %s' % (admin_media, media))

example-django-project/caktus_website/local_settings.py.example

+from caktus_website.settings import *
+
+DEBUG = True
+SERVE_STATIC_MEDIA = True
+
+DATABASE_ENGINE = 'sqlite3'
+DATABASE_NAME = 'caktus_website.db'

example-django-project/caktus_website/manage.py

+#!/usr/bin/env python
+import sys
+import os.path
+# remove '.' from the path (you should use the project package to reference
+# anything in here)
+sys.path.pop(0)
+PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
+sys.path.insert(0, os.path.dirname(PROJECT_ROOT))
+
+from django.core.management import execute_manager
+try:
+    import caktus_website.settings # Assumed to be in the same directory.
+except ImportError:
+    import sys
+    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
+    sys.exit(1)
+
+if __name__ == "__main__":
+    execute_manager(caktus_website.settings)

example-django-project/caktus_website/requirements/apps.txt

+-e svn+http://code.djangoproject.com/svn/django/branches/releases/1.1.X#egg=django

example-django-project/caktus_website/settings.py

+# Django settings for caktus_website project.
+
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+
+ADMINS = (
+    # ('Your Name', 'your_email@domain.com'),
+)
+
+MANAGERS = ADMINS
+
+DATABASE_ENGINE = ''           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
+DATABASE_NAME = ''             # Or path to database file if using sqlite3.
+DATABASE_USER = ''             # Not used with sqlite3.
+DATABASE_PASSWORD = ''         # Not used with sqlite3.
+DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
+DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.
+
+# Local time zone for this installation. Choices can be found here:
+# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
+# although not all choices may be available on all operating systems.
+# If running in a Windows environment this must be set to the same as your
+# system time zone.
+TIME_ZONE = 'America/Chicago'
+
+# Language code for this installation. All choices can be found here:
+# http://www.i18nguy.com/unicode/language-identifiers.html
+LANGUAGE_CODE = 'en-us'
+
+SITE_ID = 1
+
+# If you set this to False, Django will make some optimizations so as not
+# to load the internationalization machinery.
+USE_I18N = True
+
+# Absolute path to the directory that holds media.
+# Example: "/home/media/media.lawrence.com/"
+MEDIA_ROOT = ''
+
+# URL that handles the media served from MEDIA_ROOT. Make sure to use a
+# trailing slash if there is a path component (optional in other cases).
+# Examples: "http://media.lawrence.com", "http://example.com/media/"
+MEDIA_URL = ''
+
+# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
+# trailing slash.
+# Examples: "http://foo.com/media/", "/media/".
+ADMIN_MEDIA_PREFIX = '/media/'
+
+# Make this unique, and don't share it with anybody.
+SECRET_KEY = '5b99_i_$u098&a-^-63=^en4zo#qf^m1ou*b5(rnv3(fgt-@@r'
+
+# List of callables that know how to import templates from various sources.
+TEMPLATE_LOADERS = (
+    'django.template.loaders.filesystem.load_template_source',
+    'django.template.loaders.app_directories.load_template_source',
+#     'django.template.loaders.eggs.load_template_source',
+)
+
+MIDDLEWARE_CLASSES = (
+    'django.middleware.common.CommonMiddleware',
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+)
+
+ROOT_URLCONF = 'caktus_website.urls'
+
+TEMPLATE_DIRS = (
+    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
+    # Always use forward slashes, even on Windows.
+    # Don't forget to use absolute paths, not relative paths.
+)
+
+INSTALLED_APPS = (
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.sites',
+    'django.contrib.admin',
+    'caktus_website.blog',
+)

example-django-project/caktus_website/settings_staging.py

+from caktus_website.settings import *
+
+DEBUG = True
+
+ADMIN_MEDIA_PREFIX = '/admin-media/'
+
+DATABASE_ENGINE = 'sqlite3'
+DATABASE_NAME = '/tmp/caktus_website.db'

example-django-project/caktus_website/urls.py

+from django.conf.urls.defaults import *
+
+# Uncomment the next two lines to enable the admin:
+from django.contrib import admin
+admin.autodiscover()
+
+urlpatterns = patterns('',
+    # Example:
+    # (r'^caktus_website/', include('caktus_website.foo.urls')),
+
+    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
+    # to INSTALLED_APPS to enable admin documentation:
+    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
+
+    # Uncomment the next line to enable the admin:
+    (r'^admin/', include(admin.site.urls)),
+)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.