Run Django on Tornado

本文介绍了一种将Django应用部署在Tornado服务器上的方法,通过这种方式可以利用Tornado的强大功能并保留Django的便利性,特别是对于需要WebSockets的应用场景。

Here’s the code to get Django running on Tornado. Explanation below.


#!/usr/bin/python2.7
#
# Author: Michael Williamson

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vis.settings")
from tornado.options import options, define, parse_command_line
import django.conf
import django.contrib.auth
import django.core.handlers.wsgi
import django.db
import django.utils.importlib

import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.wsgi
import datetime

import httplib
import json
import logging

from tornado.options import options, define

define('port', type=int, default=8080)


class BaseWebSocketHandler(tornado.websocket.WebSocketHandler):
  def prepare(self):
    super(BaseWebSocketHandler, self).prepare()
    # Prepare ORM connections
    django.db.connection.queries = []

  def finish(self, chunk = None):
    super(BaseWebSocketHandler, self).finish(chunk = chunk)
    # Clean up django ORM connections
    django.db.connection.close()
    if False:
      logging.info('%d sql queries' % len(django.db.connection.queries))
      for query in django.db.connection.queries:
        logging.debug('%s [%s seconds]' % (query['sql'], query['time']))

    # Clean up after python-memcached
    from django.core.cache import cache
    if hasattr(cache, 'close'):
      cache.close()

  def get_django_session(self):
    if not hasattr(self, '_session'):
      engine = django.utils.importlib.import_module(
        django.conf.settings.SESSION_ENGINE)
      session_key =
self.get_cookie(django.conf.settings.SESSION_COOKIE_NAME)
      self._session = engine.SessionStore(session_key)
    return self._session

  def get_user_locale(self):
    # locale.get will use the first non-empty argument that matches a
    # supported language.
    return tornado.locale.get(
      self.get_argument('lang', None),
      self.get_django_session().get('django_language', None),
      self.get_cookie('django_language', None))

  def get_current_user(self):
    # get_user needs a django request object, but only looks at the session
    class Dummy(object): pass
    django_request = Dummy()
    django_request.session = self.get_django_session()
    user = django.contrib.auth.get_user(django_request)
    if user.is_authenticated():
      return user
    else:
      # try basic auth
      if not self.request.headers.has_key('Authorization'):
        return None
      kind, data = self.request.headers['Authorization'].split(' ')
      if kind != 'Basic':
        return None
      (username, _, password) = data.decode('base64').partition(':')
      user = django.contrib.auth.authenticate(username = username,
                                              password = password)
      if user is not None and user.is_authenticated():
        return user
      return None

  def get_django_request(self):
    request = django.core.handlers.wsgi.WSGIRequest(
      tornado.wsgi.WSGIContainer.environ(self.request))
    request.session = self.get_django_session()

    if self.current_user:
      request.user = self.current_user
    else:
      request.user = django.contrib.auth.models.AnonymousUser()
    return request

class HelloHandler(tornado.web.RequestHandler):
  def get(self):
    self.write('Hello from tornado')

class WebSocketHandler(BaseWebSocketHandler):
  def open(self):
    print 'Websocket opened'
    print 'Current user: ' + str(self.get_current_user())

  def on_message(self, message):
    print 'Websocket got a message: ' + str(message)

  def on_close(self):
    print 'Websocket closed'


class NoCacheStaticHandler(tornado.web.StaticFileHandler):
  """ Request static file handlers for development and debug only.
  It disables any caching for static file.
  """
  def set_extra_headers(self, path):
    self.set_header('Cache-Control', 'no-cache, must-revalidate')
    self.set_header('Expires', '0')
    now = datetime.datetime.now()
    expiration = datetime.datetime(now.year-1, now.month, now.day)
    self.set_header('Last-Modified', expiration)


def main():
  wsgi_app = tornado.wsgi.WSGIContainer(
      django.core.handlers.wsgi.WSGIHandler())
  tornado_app = tornado.web.Application(
    [
      (r'/static/(.*)', NoCacheStaticHandler, {'path': 'fe/static'}),
      ('/hello-tornado', HelloHandler),
      ('/websocket', WebSocketHandler),
      ('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app)),
      ])
  server = tornado.httpserver.HTTPServer(tornado_app)
  server.listen(options.port)
  tornado.ioloop.IOLoop.instance().start()

if __name__ == '__main__':
  main()

I run from within my virtual environment using

python tornado_main.py
I don’t use the standard python manage.py runserver provided by django.

I built this because I wanted

A WebSocker server which also handled authentication.
To reuse all the nice django apps for authentication.
To keep it lightweight. There are numerous ways to embed websocket frameworks inside of django, but they all seemed too heavyweight for what I was trying to do here.
I adapted this from https://gist.github.com/654157, and I stuck this main file in the same top-level folder as my django app.
转载自https://thinkfaster.co/2015/01/run-django-on-tornado/ 感谢作者。嘻嘻

考虑柔性负荷的综合能源系统低碳经济优化调度【考虑碳交易机制】(Matlab代码实现)内容概要:本文围绕“考虑柔性负荷的综合能源系统低碳经济优化调度”展开,重点研究在碳交易机制下如何实现综合能源系统的低碳化与经济性协同优化。通过构建包含风电、光伏、储能、柔性负荷等多种能源形式的系统模型,结合碳交易成本与能源调度成本,提出优化调度策略,以降低碳排放并提升系统运行经济性。文中采用Matlab进行仿真代码实现,验证了所提模型在平衡能源供需、平抑可再生能源波动、引导柔性负荷参与调度等方面的有效性,为低碳能源系统的设计与运行提供了技术支撑。; 适合人群:具备一定电力系统、能源系统背景,熟悉Matlab编程,从事能源优化、低碳调度、综合能源系统等相关领域研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①研究碳交易机制对综合能源系统调度决策的影响;②实现柔性负荷在削峰填谷、促进可再生能源消纳中的作用;③掌握基于Matlab的能源系统建模与优化求解方法;④为实际综合能源项目提供低碳经济调度方案参考。; 阅读建议:建议读者结合Matlab代码深入理解模型构建与求解过程,重点关注目标函数设计、约束条件设置及碳交易成本的量化方式,可进一步扩展至多能互补、需求响应等场景进行二次开发与仿真验证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值