Created
October 14, 2011 10:25
-
-
Save mikaelhg/1286761 to your computer and use it in GitHub Desktop.
PostgreSQL PL/Python stored procedures for email handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION download(url TEXT) RETURNS TEXT | |
AS $$ | |
import urllib2 | |
try: | |
result = urllib2.urlopen(url) | |
rawdata = result.read() | |
info = result.info() | |
try: | |
content_type, encoding = info['Content-Type'].split('charset=') | |
except: | |
import chardet | |
encoding = chardet.detect(rawdata)['encoding'] | |
return rawdata.decode(encoding) | |
except urllib2.URLError, e: | |
plpy.error(e) | |
return '' | |
$$ LANGUAGE plpythonu; | |
CREATE OR REPLACE FUNCTION mime_subject(mime_text TEXT) RETURNS TEXT | |
AS $$ | |
import email | |
try: | |
msg = email.message_from_string(mime_text) | |
subject = msg['Subject'] | |
return subject | |
except Exception, e: | |
plpy.info(e) | |
return '' | |
$$ LANGUAGE plpythonu; | |
CREATE OR REPLACE FUNCTION mime_subject(mime_text TEXT) RETURNS TEXT | |
AS $$ | |
import email | |
from email.header import decode_header | |
try: | |
msg = email.message_from_string(mime_text) | |
subject = msg['Subject'] | |
decodes = decode_header(subject) | |
if len(decodes) == 1: | |
str, encoding = decodes[0] | |
if encoding: | |
return str.decode(encoding) | |
return subject | |
except Exception, e: | |
plpy.info(e) | |
return '' | |
$$ LANGUAGE plpythonu; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment