正在加载...

tornado-7 tornado 和 django 合体(上)

之前有提过,tornado的db非常的简单,只有一个基于mysql的基础封装,而这个封装甚至连事务都没有。所以,如果我们采用tornado的db能做的事情就是写sql语句。

对于小型的系统还好,对于一些中/中大/大型业务系统,sql写起来是比较费事费时的,成本很高,尤其是以后的维护成本。

所以,我们需要引入一个第3方的ORM。在Python,ORM最著名的莫过于 sqlalchemy 和 sqlobject了。

那我们在tornado中就用它们?答案是否定的。原因是:我们期望能够有一个类似DJango的Admin管理界面。

好吧,程序员总是很懒惰的,哪怕一个字母都不愿意多敲。程序员总是很贪心的,哪怕能多一片叶子,也要仅仅的攥着手中。

现在的实际情况就来了,我们能不能利用DJango提供的ORM和Admin,为Tornado使用呢 ?

经过一天的研究,答案是肯定的。下面,我们就来具体的讲讲。

步骤如下

生成Django项目

django-admin.py startproject Tornadjango

创建一个app

我习惯只有一个app,且命名为app

cd Tornadjango

python manage.py startapp app

修改app目录下的文件名

这个也是我习惯了的命名规则, 创建controllers.py, 删除views.py

在工程目录下面创建application.py

到此,目录结构应该如下: 目录结构

修改 url.py

#coding: utf-8

from django.conf.urls.defaults import patterns, include
from django.contrib import admin
import django
import os

admin.autodiscover()

MEDIA_ROOT = os.path.join(os.path.dirname(django.__file__), 'contrib', 'admin', 'media')

urlpatterns = patterns('',
    (r'^admin/media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': MEDIA_ROOT, 'show_indexes': False}),
    (r'^admin/', include(admin.site.urls)),
)

修改settings.py

# Django settings for Tornadjango project.
import os

DEBUG = True
TEMPLATE_DEBUG = DEBUG

PROJECT_PATH = os.path.join(os.path.dirname(__file__))

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'tornadjango',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        '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.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Asia/Shanghai'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'zh-cn'

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

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/admin/media/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'oa8xplu6_lhlegtxpc(f+!tc=2$%&oumz4zx2_1d*vio75z3c7'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = '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.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
     'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
     'django.contrib.admindocs',
    # customer app
    'app',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

修改app.controller.py

#coding: utf8

import tornado.web


class HelloController(tornado.web.RequestHandler):

    def get(self):
        self.write('Hello, world ! \n')

修改application.py

#coding: utf-8
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

import settings
import app.urls
from django.core.handlers.wsgi import WSGIHandler
from tornado import options, wsgi
import tornado.httpserver


options.define('admin_port', default=9900, type=int, help='Run admin platform on the given port')
options.define('app_port', default=9901, type=int, help='Run app platform on the given port')


tornado_env = dict(
#    template_path       = os.path.join(os.path.dirname(__file__), 'templates'),
#    static_path         = os.path.join(os.path.dirname(__file__), 'static'),
    xsrf_cookies        = False,
    cookie_secret       = "11oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
    autoescape          = None,
    debug               = settings.DEBUG,
    login_url           = '/',
)


if __name__ == "__main__":
    options.parse_command_line()
    address, admin_port, app_port = '0.0.0.0', options.options.admin_port, options.options.app_port 

    def admin_listen():
        wsgi_app = wsgi.WSGIContainer(WSGIHandler())
        tornado_app = tornado.web.Application([
            ('/admin/(.*)', tornado.web.FallbackHandler, dict(fallback=wsgi_app)),
        ])
        tornado.httpserver.HTTPServer(tornado_app).listen(admin_port)
        print 'run admin platform on (%s:%s)' % (address, admin_port)

    def app_listen():
        tornado_app = tornado.web.Application(app.urls.urls)
        tornado_app.listen(app_port)
        print 'run app platform on (%s:%s)' % (address, app_port)

    app_listen()
    admin_listen()

    tornado.ioloop.IOLoop.instance().start()

创建db

python manager.py syncdb

启动

python application.py

浏览器访问

http://localhost:9901/            # tornado app

http://localhost:9900/admin/      # django admin

这样整个步骤就完成了。篇幅有限,具体的解释看下篇

文件下载: Tornadjango.tar.gz