龙卷风的Django用户

时间:2013-05-14 17:37:23

标签: python django websocket tornado sockjs

我一直在使用下面的代码来获取龙卷风中的django用户:

from django.conf import settings
import django.contrib.auth
import django.utils.importlib

import tornado
from tornado.options import options
import tornado.web
import tornado.ioloop
import sockjs.tornado

class RouterConnection(sockjs.tornado.SockJSConnection):

    def get_current_user(self, info):
        engine = django.utils.importlib.import_module(django.conf.settings.SESSION_ENGINE)
        session_key = str(info.get_cookie(django.conf.settings.SESSION_COOKIE_NAME)).split('=')[1]

        class Dummy(object):
            pass

        django_request = Dummy()
        django_request.session = engine.SessionStore(session_key)
        user = django.contrib.auth.get_user(django_request)
        return user


    def on_open(self, info):
        user = self.get_current_user(info=info)

if __name__ == "__main__":
    import logging
    Router = sockjs.tornado.SockJSRouter(RouterConnection)

    app = tornado.web.Application(Router.urls, debug=True, )

    app.listen(settings.TORNADO_PORT)

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

我的问题如下:
Django更改了日志配置,我再也看不到龙卷风的任何日志输出了。我怎样才能重新初始化龙卷风伐木?还有其他方法可以将Django与Tornado集成吗?

非常感谢提前。

2 个答案:

答案 0 :(得分:2)

要重置django日志记录,请使用以下命令:

logger = logging.getLogger('')
for handler in logger.handlers:
    logger.removeHandler(handler)
tornado.options.parse_command_line()

使用django.conf模块时,LazySettings类初始化为初始化的django logger。 此外,我不得不使用初始化设置类重写代码:

from django.conf import settings
import django.contrib.auth
import django.utils.importlib

import tornado
from tornado.options import options
import tornado.web
import tornado.ioloop
import sockjs.tornado

TORNADO_PORT = settings.TORNADO_PORT

class RouterConnection(sockjs.tornado.SockJSConnection):

    def get_current_user(self, info):
        engine = django.utils.importlib.import_module(settings.SESSION_ENGINE)
        session_key = str(info.get_cookie(settings.SESSION_COOKIE_NAME)).split('=')[1]

        class Dummy(object):
            pass

        django_request = Dummy()
        django_request.session = engine.SessionStore(session_key)
        user = django.contrib.auth.get_user(django_request)
        return user


    def on_open(self, info):
        user = self.get_current_user(info=info)

if __name__ == "__main__":
    import logging
    logger = logging.getLogger('')
    for handler in logger.handlers:
        logger.removeHandler(handler)
    tornado.options.parse_command_line()

    Router = sockjs.tornado.SockJSRouter(RouterConnection)

    app = tornado.web.Application(Router.urls, debug=settings.DEBUG)

    app.listen(settings.TORNADO_PORT)

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

答案 1 :(得分:-1)

使用tornado.wsgi.WSGIContainer来包装Django。有关工作示例,请参阅this demo project