单文件启动 Django 应用

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import django
from django.conf import settings

BASE_DIR = os.path.dirname(os.path.dirname(__file__))


class URLConf(object):
    @property
    def urlpatterns(self):
        from django.conf.urls import patterns, include, url
        from django.contrib import admin

        urls = [
            url(r'^admin/', include(admin.site.urls)),
            url(r'^$', index),
        ]
        return patterns('', *urls)


def secret_key():
    _file_name = os.path.join(BASE_DIR, '.secret_key')
    if os.path.isfile(_file_name):
        with open(_file_name, 'r') as f:
            return f.read(50)
    chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'

    from django.utils.crypto import get_random_string

    key = get_random_string(50, chars)
    with open(_file_name, 'w') as f:
        f.write(key)
    return key


SETTINGS = {
    'BASE_DIR': BASE_DIR,
    'SECRET_KEY': secret_key(),
    'DEBUG': True,
    'TEMPLATE_DEBUG': True,
    'ALLOWED_HOSTS': [],
    'INSTALLED_APPS': (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ),
    'MIDDLEWARE_CLASSES': (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ),
    'ROOT_URLCONF': URLConf(),
    'WSGI_APPLICATION': None,
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    },
    'LANGUAGE_CODE': 'en-us',
    'TIME_ZONE': 'UTC',
    'USE_I18N': True,
    'USE_L10N': True,
    'USE_TZ': True,
    'STATIC_URL': '/static/',
}

if not settings.configured:
    settings.configure(**SETTINGS)

django.setup()


#################### VIEWS ####################


from django.shortcuts import render_to_response
from django.http import HttpResponse


def index(request):
    return HttpResponse('hello world')


####################  END  ####################


if __name__ == '__main__':
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)