2017-06-02 73 views
-2

我正在使用Django ORM和MySQL的多线程应用程序。这个想法是使用一个单独的启动脚本来启动多个模块(这里的功能意义上的“模块”,而不是Python的意义),每个模块都有一个“服务循环”,它在自己的线程中运行。我已经为每个模块使用一个类来组织它。在线程应用程序中使用Django ORM的最佳实践

我原来是用sqlite DB做的,它工作得很好。现在我正在转换到MySQL并且遇到与线程相关的数据库连接问题。例如,看起来我需要在每个线程中调用db.connections.close_all()以避免与数据库连接争用?我想我需要将与Django ORM相关的所有设置移动到服务线程,但是我不能在类的init()方法中导入模型。

无论如何,我确信其他人已经处理过这个问题,我确信有一些很好的模式。任何人都有可以分享的建议或最佳实践?

这是我简单的启动脚本:

from controller.modules.manager import Manager 
from controller.modules.scanner import Scanner 

print("Starting...") 

# The directory scanner 
scanner = Scanner() 

# The job manager 
manager = Manager() 

而这里的模块之一(Scanner类)的例子:

import os 
from multiprocessing import Process 
from time import sleep 
import threading 
import django 

# Need to do this before importing models 
from common.utilities.os import OS 
os.environ["DJANGO_SETTINGS_MODULE"] = "common.settings" 
django.setup() 

# Import models here 

class Scanner: 
    def __init__(self): 
     # Define some member variables here, some of which include 
     # DB models 

     # Launch service loop 
     Process(target=self.service_loop, name='service loop').start() 

    def service_loop(self): 
     while True: 
      # Scan some directories and update some DB entries 

      # Throttle the loop 
      sleep(config.THROTTLE_SLEEP_TIME_SEC) 

回答

-1

解决。经过无数小时的实验和谷歌搜索,我终于找到了我正在寻找的here。我从python的threading.Thread类继承了模块类,它解决了所有问题。

相关问题