Intro to PL/Python
Central Ohio Python Users Group, January 25, 2010
PostgreSQL Conference East, March, 2010
Code Examples
CREATE FUNCTION readrss (rssurl TEXT) RETURNS SETOF rssfeed AS $$
import feedparser
feed = feedparser.parse( rssurl )
for entry in feed["entries"]:
yield ( entry["date"], entry["title"], entry["summary"] if entry.has_key('summary') else None, entry["link"] )
$$ LANGUAGE plpythonu STRICT VOLATILE;
Some RSS feeds don’t have summary portions (the example using a YouTube feed resulted in an error during the original presentation.) Python 2.5 introduced something resembling a ternary operator, which we can use here to replace any missing summary with the SQL NULL value. If it’s possible that other fields can be ommitted from an RSS feed we’ll probably want to do the same thing there.
PostgreSQL Directory Walk (8.4+)
This simple example combines two very simple PL/Python functions with the recursive CTE capability introduced in 8.4.
Low Account Balance Email
The function is shown in two revisions. If this were used in production the smtplib module should probably be combined with a module to generate the email message itself.