繁体   English   中英

Python 当另一个.py 文件中的变量更改时通知主代码

[英]Python notify main code when variable change in another .py file

我不知道如何完成以下场景:

在我的 main.py 和 request.py 中,我引用了一个包含一些配置变量的 config.py 女巫。 在此示例中,离线变量为 True 或 False。

我想做的是:如果例如。 在我的 request.py 中我设置了 config.offline = True,然后我想在我的 main.py 上做一些事情。

但是 main.py 也引用了 request.py 所以我不能从 request.py 调用任何函数..

关于如何执行此操作的任何想法?

我有超过 1000 行代码,所以我无法展示所有内容,但我已尝试展示最重要的内容:

主要文件:

import config as cfg
import request as req

def doStuffWhenOfflineVarChanges(newState):
  print(newState)

配置文件:

offline = True

请求.py:

import config as cfg

def logEntrance(barCode, noOfGuests, dt=datetime.now()):
    date = dt.strftime("%Y-%m-%d")
    time = dt.strftime("%H:%M:%S")
    headers = {'Content-type': 'application/json', 'Authorization': cfg.auth}

    url = 'https://xxxxx.xxxxxxxx.xxx/' + cfg.customerId + '/api.ashx'
    params = {"inputtype": "logentrances"}
    pl = [{"Barcode": barCode ,  "PoeID": cfg.poeId,  "UserID": cfg.userId,  "EntranceDate": date,  "EntranceTime": time,  "NoOfGuests": str(noOfGuests),  "OfflineMode": cfg.offline}]

    #print(url)
    print(pl)

    try:
        r = requests.post(url, json=pl, params=params, headers=headers)

        print(r.status_code)
    except:
        cfg.offline = True
    return r

您需要回电 function 来处理您的 onfig.py 文件中的更改!

# config.py
offline = False

def doStuffWhenOfflineVarChanges(newState):
    print(newState)

# request.py
import config as cfg

class OfflineState:
    def __init__(self, callback):
        self._callback = callback
        self._offline = cfg.offline
    
    @property
    def offline(self):
        return self._offline
    
    @offline.setter
    def offline(self, value):
        self._offline = value
        self._callback(value)

offline_state = OfflineState(cfg.doStuffWhenOfflineVarChanges)

import requests
import datetime

def logEntrance(barCode, noOfGuests, dt=datetime.now()):
    date = dt.strftime("%Y-%m-%d")
    time = dt.strftime("%H:%M:%S")
    headers = {'Content-type': 'application/json', 'Authorization': cfg.auth}

    url = 'https://xxxxx.xxxxxxxx.xxx/' + cfg.customerId + '/api.ashx'
    params = {"inputtype": "logentrances"}
    pl = [{"Barcode": barCode ,  "PoeID": cfg.poeId,  "UserID": cfg.userId,  "EntranceDate": date,  "EntranceTime": time,  "NoOfGuests": str(noOfGuests),  "OfflineMode": offline_state.offline}]

    try:
        r = requests.post(url, json=pl, params=params, headers=headers)
    except:
        offline_state.offline = True
    return r

暂无
暂无

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

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