使用python中的切换器功能更新var

时间:2020-10-22 22:26:39

标签: json python-3.x dictionary

我是Python的新手,如果我尝试做的事情很奇怪,请稍加同情,经过几次尝试后,我仍无法更新某些键:使用函数切换器对变量(messageInit)中的字典进行配对(switcherMessage(args)),我的目标是能够触发一种特定的方法,具体取决于到达的消息的类型(在这种情况下,我用消息变量表示它们),以便它仅更新字典的一部分(messageInit),然后将指定的数据传递给另一个函数(otherTask(数据)),在这种情况下,仅打印它们。最奇怪的是,对于第一个切换器是否有效(toActive()),它给了我期望的结果(其他两个没有),但是老实说我不理解变量在python中的行为,我有经验js,但在这里我感到困惑,因为对我来说,应该只对其进行更新。

我非常感谢您的任何帮助或暗示。

import json

# global dict to hold telemtry
messageInit = {
    'thingId': 'CarlosTal84-Hilda-mggbCoK1pihIqDJzJf3T',
    'active': 'false',
    'motorSpeed': 0,
    'colorValue': {
                    "r":0,
                    "g":0,
                    "b":0
                }
}

# print init data dict
print(f"init var: {messageInit}")

# other func
def otherTask(data):
    print(f"after task: {data}")

# function to handle the receive message
def on_message():

    # message bin arrival
    message =  b'{"active":"true"}'
    # message = b'{"motorSpeed": 20}'
    # message =  b'{"colorValue":{"r":2,"g":10,"b":100}}'

    # hold message in a var
    payload = str(message.decode('utf-8'))

    # print payload var with message
    # print(payload)

    # check if exist data in the payload
    if payload:

        # convert string in obj
        obj = json.loads(payload)

        # switcher func
        def switcherMessage(args):

            # methods
            def toActive():

                global messageInit
                # hold in vars
                messageActive = obj.get("active")
                messageInit.update({"active": messageActive})
                active = messageInit.get("active")
                return active

            def toMotorSpeed():

                global messageInit
                # hold in vars
                messageMotorSpeed = obj.get("motorSpeed")
                messageInit.update({"motorSpeed": messageMotorSpeed})
                motorSpeed = messageInit.get("motorSpeed")
                return motorSpeed

            def toColorValue():

                global messageInit
                # hold in vars
                messageColorValue = obj.get("colorValue")
                messageInit.update({"colorValue": messageColorValue})
                colorValue = messageInit.get("colorValue")
                return colorValue

            # dict switch
            switcher={
                'messageActive': toActive(),
                'messageMotorSpeed': toMotorSpeed(),
                'messageColorValue': toColorValue()
            }

            # return switcher
            return switcher.get(args, lambda:"Shit")

        # Driver program to switcher
        def wichMessage():

            if payload.find("active"):
                return 'messageActive'
            elif payload.find("motorSpeed"):
                return 'messageMotorSpeed'
            elif payload.find("colorValue"):
                return 'messageColorValue'

        # type of message var
        args = wichMessage()

        # run methods to fill vars
        print(switcherMessage(args))

        # other task
        otherTask(switcherMessage(args))

# run it
on_message()

# here the outputs for every switcher:
init var: {'thingId': 'CarlosTal84-Hilda-mggbCoK1pihIqDJzJf3T', 'active': 'false', 'motorSpeed': 0, 'colorValue': {'r': 0, 'g': 0, 'b': 0}}
true
after task: true
>>> 
# second message var
init var: {'thingId': 'CarlosTal84-Hilda-mggbCoK1pihIqDJzJf3T', 'active': 'false', 'motorSpeed': 0, 'colorValue': {'r': 0, 'g': 0, 'b': 0}}
None
after task: None
>>> 
# third message var 
init var: {'thingId': 'CarlosTal84-Hilda-mggbCoK1pihIqDJzJf3T', 'active': 'false', 'motorSpeed': 0, 'colorValue': {'r': 0, 'g': 0, 'b': 0}}
None
after task: None
>>> 

0 个答案:

没有答案