Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Using Publish/Subscribe in a Distributed Middleware Architecture

Credit: Graham Dumpleton

Problem

You need to allow distributed services to set themselves up as publishers of information and/or subscribers to that information by writing a suitable central exchange (middleware) server.

Solution

The OSE package supports a publisher/subscriber programming model through its netsvc module. To exploit it, we first need a central middleware process to which all others connect:

# The central.py script -- needs the OSE package from http://ose.sourceforge.net

import netsvc
import signal

dispatcher = netsvc.Dispatcher(  )
dispatcher.monitor(signal.SIGINT)

exchange = netsvc.Exchange(netsvc.EXCHANGE_SERVER)
exchange.listen(11111)

dispatcher.run(  )

Then, we need service processes that periodically publish information to the central middleware process, such as:

# The publish.py script -- needs the OSE package from http://ose.sourceforge.net import netsvc import signal import random class Publisher(netsvc.Service): def _ _init_ _(self): netsvc.Service._ _init_ _(self,"SEED") self._count = 0 time = netsvc.DateTime( ) data = { "time": time } self.publishReport("init", data, -1) self.startTimer(self.publish, 1, "1") def publish(self,name): self._count = self._count + 1 time = netsvc.DateTime( ) value = int(0xFFFF*random.random( )) data = { "time": time, "count": self._count, "value": value } self.publishReport("next", data) self.startTimer(self.publish, 1, "1") dispatcher = netsvc.Dispatcher( ) dispatcher.monitor(signal.SIGINT) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata