Building a Subscriber in Python

Now let’s explore the same subscriber implementation, but now using Python. For this example, the subscriber classes are stored in a file name subscriber.py:

import re import urllib import urllib2 ''' ' Class: Subscription Error ' Description: Custom error class for subscription exceptions ''' class SubscribeError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) ''' ' Class: Subscriber ' Description: Provides ability to subscribe / unsubscribe from hub feeds ''' class Subscriber: regex_url = re.compile('^https?://') #simple URL string validator #constructor that stores the hub and callback URLs for the subscriber def __init__(self, hub, callback): if self.regex_url.match(hub): self.hub = hub else: raise SubscribeError('Invalid hub URL supplied') if self.regex_url.match(callback): self.callback = callback else: raise SubscribeError('Invalid callback URL supplied') #initiates a request to subscribe to a feed def subscribe(self, feed): return self.change_subscription('subscribe', feed) #initiates a request to unsubscribe from a feed def unsubscribe(self, feed): return self.change_subscription('unsubscribe', feed) #makes request to hub to subscribe / unsubscribe def change_subscription(self, mode, feed): #check if provided feed is a valid ...

Get Programming Social Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.