是否有类似于 Python 请求的 Paho MQTT 会话?
Is there something similar to Python requests' Sessions for Paho MQTT?
我正在阅读 Paho MQTT 的 Publish
模块的 documentation,并考虑我的应用程序,我可能必须在其中发布许多 single
消息,每个消息都有相似的关键字参数.这些调用类似于以下内容:
paho.mqtt.publish.single('dummy_topic', payload=dummy_payload, qos=0, retain=False,
auth={'username': "dummy_username", 'password': "dummy_password"},
hostname=config['mqtt_host'], port=int(config['mqtt_port']), tls=dummy_tls)
为了让我的代码保持干燥,我正在尝试想办法在不同的 single
命令中保留关键字参数。
对于 HTTP 请求,Python 的请求模块有 Sessions object which allows one to do this. Is there something similar for Paho MQTT, or shall I instead use something like partial
from the functools 模块?
我想您已经确定了解决方案。 functools.partial
函数应该可以满足您的需求。例如下面的代码:
from functools import partial
def myfunc(arg, kw1='foo', kw2='bar'):
print 'arg:', arg
print 'kw1:', kw1
print 'kw2:', kw2
newfunc = partial(myfunc, kw1='hello', kw2='world')
newfunc('somearg')
产生这个输出:
arg: somearg
kw1: hello
kw2: world
将其应用到您的示例中,您将执行如下操作:
publish_single = partial(payload=dummy_payload, qos=0, retain=False,
auth={'username': "dummy_username", 'password': "dummy_password"},
hostname=config['mqtt_host'], port=int(config['mqtt_port']), tls=dummy_tls)
并这样称呼它:
publish_single('some_topic')
publish_single('another_topic')
我正在阅读 Paho MQTT 的 Publish
模块的 documentation,并考虑我的应用程序,我可能必须在其中发布许多 single
消息,每个消息都有相似的关键字参数.这些调用类似于以下内容:
paho.mqtt.publish.single('dummy_topic', payload=dummy_payload, qos=0, retain=False,
auth={'username': "dummy_username", 'password': "dummy_password"},
hostname=config['mqtt_host'], port=int(config['mqtt_port']), tls=dummy_tls)
为了让我的代码保持干燥,我正在尝试想办法在不同的 single
命令中保留关键字参数。
对于 HTTP 请求,Python 的请求模块有 Sessions object which allows one to do this. Is there something similar for Paho MQTT, or shall I instead use something like partial
from the functools 模块?
我想您已经确定了解决方案。 functools.partial
函数应该可以满足您的需求。例如下面的代码:
from functools import partial
def myfunc(arg, kw1='foo', kw2='bar'):
print 'arg:', arg
print 'kw1:', kw1
print 'kw2:', kw2
newfunc = partial(myfunc, kw1='hello', kw2='world')
newfunc('somearg')
产生这个输出:
arg: somearg
kw1: hello
kw2: world
将其应用到您的示例中,您将执行如下操作:
publish_single = partial(payload=dummy_payload, qos=0, retain=False,
auth={'username': "dummy_username", 'password': "dummy_password"},
hostname=config['mqtt_host'], port=int(config['mqtt_port']), tls=dummy_tls)
并这样称呼它:
publish_single('some_topic')
publish_single('another_topic')