繁体   English   中英

尽管已设置,但 Python 类变量为 None

[英]Python class variable is None despite being set

我正在为 Python 中的线程通信而苦苦挣扎。 我显然错过了一些东西,但我是 Python 新手,所以我不太清楚自己在做什么。

当服务器收到 GET 请求时,我希望它从一个单独的线程中获取两个数字(x 和 y 坐标),该线程不断更新这些值并将这些数字作为响应返回。

我有一个简单的 Django 项目,其结构如下:

在此处输入图片说明

它非常基础,根据教程制作。

当服务器启动时,我启动一个线程,它看起来在一个单独的线程中启动我的坐标生成器:

class GpsMockCoordsServiceConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'gps_mock_coords_service'

    def ready(self):
        if os.environ.get('RUN_MAIN', None) != 'true':
            _thread.start_new_thread(CoordsTracker.launch_recognition, ())

CoordsTracker 类看起来像这样:

coords = None
class CoordsTracker:
    #coords = None #tried placin it here, but same effect - it is None when retreived from views.py

    logger = logging.getLogger("CoordsTrackerLogger")

    @staticmethod
    def draw_contours(mask, frame, color):
            ......
        for stuff in stuffs:
                 ......
            CoordsTracker.set_coords((x, y))
                 ......

    @staticmethod
        def launch_recognition():
                ........
           while True:
                    ........
               CoordsTracker.draw_contours(....)
                    ........

   @staticmethod
   def set_coords(new_coords):
       global coords
       CoordsTracker.logger.debug("setting coords " + str(new_coords))
       coords = new_coords # here coords var is OK

   @staticmethod
   def get_coords():
       CoordsTracker.logger.debug(coords) # Here it is OK if I call this method from draw_contours() and is not OK if I call this from views.py file.
       return coords

views.py 类只有这个方法:

def index(request):
    # with CoordsTracker.coords_thread_lock:
    coords = CoordsTracker.get_coords()
    logger.debug("Got coords: " + str(coords)) #if I do a GET request this prints 'Got coords: None'
    return HttpResponse(str(coords))

UPD:和朋友调试了一段时间后,发现set_coords()方法在一个进程中调用,而get_coords()方法在另一个进程中调用。

我建议使用您拥有的中间件实现某种 IPC。 但如果它是一次性项目,您可以从 wsgi.py 某处启动线程 (launch_recognition)。 这将确保它都在同一进程中运行。

暂无
暂无

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

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