简体   繁体   English

如何在我的Tornado应用程序中使用Django ORM?

[英]How can I use the Django ORM in my Tornado application?

I have an existing Django application with a database and corresponding models.py file. 我有一个现有的Django应用程序与数据库和相应的models.py文件。

I have a new Tornado application that provides a web service to other applications. 我有一个新的Tornado应用程序,它为其他应用程序提供Web服务。 It needs to read/write from that same database, and there is code in the models file I'd like to use. 它需要从同一个数据库读/写,并且我想使用的模型文件中有代码。

How can I best use the Django database and models in my Tornado request handlers? 如何在我的Tornado请求处理程序中最好地使用Django数据库和模型? Is it as simple as making a symbolic link to the models.py Django project folder, importing Django modules, and using it? 是否像创建一个指向models.py Django项目文件夹的符号链接,导入Django模块并使用它一样简单? I guess I'd have to do settings.configure() , right? 我想我必须做settings.configure() ,对吗?

Thanks! 谢谢!

there is an example here about how to use django ORM and django form inside Tornado. 有一个例子在这里了解如何使用Django ORM和Django的内部龙卷风形式。 and you can read Using Django Inside the Tornado Web Server for some information. 您可以阅读在Tornado Web Server中使用Django获取一些信息。 the following code has taken from there: 以下代码取自:

import sys
import os

import tornado.httpserver
import tornado.ioloop
import tornado.web

# django settings must be called before importing models
from django.conf import settings
settings.configure(DATABASE_ENGINE='sqlite3', DATABASE_NAME='dev.db')

from django import forms
from django.db import models

# Define your Model
class Message(models.Model):
    """
    A Django model class.
    In order to use it you will need to create the database manually.

    sqlite> CREATE TABLE message (id integer primary key, subject varchar(30), content varchar(250));
    sqlite> insert into message values(1, 'subject', 'cool stuff');
    sqlite> SELECT * from message;
    """

    subject = models.CharField(max_length=30)
    content = models.TextField(max_length=250)
    class Meta:
        app_label = 'dj'
        db_table = 'message'
    def __unicode__(self):
        return self.subject + "--" + self.content

# Define your Form
class DjForm(forms.Form):
    subject = forms.CharField(max_length=100, required=True)
    content = forms.CharField()

# Define the class that will respond to the URL
class ListMessagesHandler(tornado.web.RequestHandler):
    def get(self):
        messages = Message.objects.all()
        self.render("templates/index.html", title="My title",
                    messages=messages)

class FormHandler(tornado.web.RequestHandler):
    def get(self):
        form = DjForm()
        self.render("templates/form.html", title="My title", form=form)

    def post(self):
        data = {
            'subject':self.request.arguments['subject'][0],
            'content':self.request.arguments['content'][0],
        }
        form = DjForm(data=data)
        if form.is_valid():
            message = Message(**form.cleaned_data)
            message.save()
            self.redirect('/')
        else:
            self.render("templates/form.html", title="My title", form=form)

# map the Urls to the class          
application = tornado.web.Application([
    (r"/", ListMessagesHandler),
    (r"/form/", FormHandler),
])

# Start the server
if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

and this is another demo with django and tornado... 这是django和龙卷风的另一个演示 ......

Add the path to the Django project to the Tornado application's PYTHONPATH env-var and set DJANGO_SETTINGS_MODULE appropriately. 将Django项目的路径添加到Tornado应用程序的PYTHONPATH env-var中,并相应地设置DJANGO_SETTINGS_MODULE。 You should then be able to import your models and use then as normal with Django taking care of initial setup on the first import. 然后,您应该能够导入模型,然后像往常一样使用Django在第一次导入时进行初始设置。

You shouldn't require any symlinks. 您不应该要求任何符号链接。

I could not get it to work with the information provided by @aragon in Django 1.8. 我无法使用@aragon在Django 1.8中提供的信息。 Since this question is one of the top results in Google when searching for Django + Tornado integration, here is how I got it to work in Django 1.8 : 由于这个问题是Google在搜索Django + Tornado集成时的最佳结果之一,因此我在Django 1.8中使用它是如何工作的:

from django import forms
from django.db import models

from models import Operation #Own model
import django

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': 'database.db',
    }
}
settings.configure(DATABASES=DATABASES)

if django.VERSION[:2] > (1,5):
    django.setup()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM