Building a Publisher in Python

Now that we have looked at a publisher implementation in PHP, let’s explore the same implementation using Python for an alternate vantage point.

For this example, the classes that make up the publisher are stored in a file named publisher.py:

import re import urllib import urllib2 ''' ' Class: Publishing Error ' Description: Custom error class for publishing exceptions ''' class PublishError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) ''' ' Class: Publisher ' Description: Provides ability to publish updates for feeds ''' class Publisher: regex_url = re.compile('^https?://') #simple URL string validator #constructor that stores the hub for the publisher def __init__(self, hub): if self.regex_url.match(hub): self.hub = hub else: raise PublishError('Invalid hub URL supplied') #makes request to hub to update feeds def publish(self, feeds): #set the POST string mode post_string = 'hub.mode=publish' #add each feed as a URL in the POST string, unless invalid URL for feed in feeds: if self.regex_url.match(feed): post_string += '&hub.url=%s' % (urllib.quote(feed)) else: raise PublishError('Invalid feed URL supplied: %s' % (feed)) try: #make request to hub file = urllib2.urlopen(self.hub, post_string) return True except (IOError, urllib2.HTTPError), ...

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.