Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement publish and subscribe with Python

Shulou Source: shulou.com Published: 2022-06-01 02:48:21 10月03日 Update

This article mainly explains "Python how to achieve publish and subscribe", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Python how to achieve publish and subscribe" bar!

Python uses redis libraries to publish and subscribe.

`import redis

Class RedisHelper:

Def _ _ init__ (self): self.__conn = redis.Redis (host='192.168.5.124',password='V6jZVVhNBfSiJ7Ib') self.chan_pub = 'TaskManager.Redis.Channel' self.chan_sub =' TaskManager.Redis.Channel'def public (self,msg): self.__conn.publish (self.chan_pub Msg) return Truedef subscribe (self): pub = self.__conn.pubsub () pub.subscribe (self.chan_pub) pub.parse_response () return pubrhl = RedisHelper () msg = {"name": 'Tim'} redis_sub = rhl.subscribe () rhl.public (json.dumps (msg)) while True: msg = redis_sub.parse_response () print (msg)

`

Chan_pub is a redis communication channel. Publishers and subscribers who connect to the same channel can communicate.

If the password set by the redis library, be sure to add password, otherwise an error will be reported.

Thank you for reading, the above is the content of "how to publish and subscribe to Python". After the study of this article, I believe you have a deeper understanding of how to achieve publishing and subscription in Python, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Subscriptions learning content channels communications publishers passwords that is ideas situations articles more knowledge knowledge points articles subscribers follow questions will report practice Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info MySQL Apple Shulou Technology Xiaomi