bgneal@285: """ bgneal@285: This module contains core functionality for the oembed application. bgneal@285: """ bgneal@285: from __future__ import with_statement bgneal@285: import urllib bgneal@285: import urllib2 bgneal@285: import gzip bgneal@285: try: bgneal@285: from cStringIO import StringIO bgneal@285: except ImportError: bgneal@285: from StringIO import StringIO bgneal@285: bgneal@285: import django.utils.simplejson as json bgneal@285: bgneal@285: bgneal@285: USER_AGENT = 'gremmies python oembed' bgneal@285: bgneal@285: bgneal@285: def get_oembed(api_endpoint, url, format='json', **opts): bgneal@285: """ bgneal@285: Perform the GET request to retrieve the embedded media data from the given bgneal@285: API endpoint for the given URL. Return the result as a Python dictionary. bgneal@285: bgneal@285: format specifies the response format, and should be 'json' or 'xml'. bgneal@285: opts are any additional GET options that should be present in the GET bgneal@285: request. bgneal@285: bgneal@285: """ bgneal@285: opts['url'] = url bgneal@285: opts['format'] = format bgneal@285: api_url = "%s?%s" % (api_endpoint, urllib.urlencode(opts)) bgneal@285: bgneal@285: headers = { bgneal@285: 'User-Agent': USER_AGENT, bgneal@285: 'Accept-Encoding': 'gzip', bgneal@285: } bgneal@285: request = urllib2.Request(api_url, headers=headers) bgneal@285: bgneal@285: opener = urllib2.build_opener() bgneal@285: f = opener.open(request) bgneal@285: headers = f.info() bgneal@285: result = f.read() bgneal@285: f.close() bgneal@285: bgneal@285: if headers.get('content-encoding') == 'gzip': bgneal@285: with gzip.GzipFile(fileobj=StringIO(result)) as f: bgneal@285: result = f.read() bgneal@285: bgneal@285: return json.loads(result) bgneal@285: bgneal@285: if __name__ == "__main__": bgneal@285: try: bgneal@285: print get_oembed("http://www.youtube.com/oembed", bgneal@285: #"http://www.youtube.com/watch?v=7_IMzJldOf4") bgneal@285: "http://www.youtube.com/watch?v=99999999999") bgneal@285: except urllib2.HTTPError, e: bgneal@285: print e