如何使用 Django 将数据从龙卷风网络套接字插入 mySQL 数据库

How to insert data from a tornado web-socket to a mySQL database using Django

我正在使用 Django 和 mysql 创建一个监控网页。我还用龙卷风创建了一个网络套接字服务器。我想做的是每次从 web-socket 收到一些东西时将数据插入 mysql 数据库。

Tornado和数据库之间应该做什么样的连接?最好将数据发送到 Django,然后将数据插入数据库或创建一个 python 程序来执行此操作?

我完全不知道如何在 django 和 tornado 之间交换数据。

经过EvilX的回答:

我已经创建了一个函数来将数据插入到 tornado 服务器文件的数据库中,但是我收到一个错误:

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

tornado服务器文件是这样的:

import tornado.httpserver
import tornado.websocket    
import tornado.ioloop    
import tornado.web
import json
from storage.models import System, Flywheel, Sensor, SensorData
from threading import Thread
import os


def dataInsert():  

string='{"jSonString":value}'

jdata=json.loads(string)

for system_name in jdata.keys():
    system = System.objects.get(name= system_name)
    for flywheel_name in jdata[system_name].keys():
        flywheel=Flywheel.objects.get(system=system.id,name=flywheel_name)

        for sensor_name in jdata[system_name][flywheel_name].keys():

            sensor= Sensor.objects.get(flywheel=flywheel.id,sensorType=sensor_name)

            sd=SensorData(sensor=sensor, value= jdata[system_name][flywheel_name][sensor_name])
            sd.save()





class WSHandler(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
    return True
def open(self):
    print 'new connection'
    self.write_message("Hello World")


def on_message(self, message):
    #self.write_message(u"Your message was: " + message)
    #print 'message received %s' % message

def on_close(self):
  print 'connection closed'

application = tornado.web.Application([
(r'/ws', WSHandler),])



if __name__ == "__main__":  
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' # TODO: edit this
#sys.path.append('./demosite') # path to your project if needed

thread = Thread(target=dataInsert())
thread.start()
thread.join()

http_server = tornado.httpserver.HTTPServer(application)  

http_server.listen(6666)

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

有两种方法。

  1. 用rabbitmq。使用django(celery)创建worker,从tornado发送任务到queue。

  2. 添加到 tornado 运行 脚本: os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

然后简单地使用 django orm 来处理数据库。将它与线程一起使用,因为 django orm 不是异步的。 如果您收到问题 "Mysql has gone away".

,也不要忘记每天重启一次龙卷风

我已经解决了在导入模型和添加模型之前添加对 django 设置的调用的问题 get_wsgi_application

import tornado.httpserver
import tornado.websocket    
import tornado.ioloop    
import tornado.web
import json


os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

from django.core.wsgi import get_wsgi_application

app= get_wsgi_application()

from storage.models import System, Flywheel, Sensor, SensorData
from threading import Thread
import os


def dataInsert():  

string='{"jSonString":value}'

jdata=json.loads(string)

for system_name in jdata.keys():
    system = System.objects.get(name= system_name)
    for flywheel_name in jdata[system_name].keys():
        flywheel=Flywheel.objects.get(system=system.id,name=flywheel_name)

        for sensor_name in jdata[system_name][flywheel_name].keys():

            sensor= Sensor.objects.get(flywheel=flywheel.id,sensorType=sensor_name)

            sd=SensorData(sensor=sensor, value= jdata[system_name][flywheel_name][sensor_name])
            sd.save()





class WSHandler(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
    return True
def open(self):
    print 'new connection'
    self.write_message("Hello World")


def on_message(self, message):
    #self.write_message(u"Your message was: " + message)
    #print 'message received %s' % message

def on_close(self):
  print 'connection closed'

application = tornado.web.Application([
(r'/ws', WSHandler),])



if __name__ == "__main__":  


thread = Thread(target=dataInsert())
thread.start()
thread.join()

http_server = tornado.httpserver.HTTPServer(application)  

http_server.listen(6666)

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