Mercurial > public > sg101
annotate oembed/core.py @ 1127:829d3b7fc0f7
Convert search page to V3 design.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Tue, 13 Sep 2016 21:49:22 -0500 |
parents | 2181da65c98b |
children |
rev | line source |
---|---|
bgneal@285 | 1 """ |
bgneal@285 | 2 This module contains core functionality for the oembed application. |
bgneal@679 | 3 |
bgneal@285 | 4 """ |
bgneal@908 | 5 from contextlib import closing |
bgneal@679 | 6 import json |
bgneal@285 | 7 import urllib |
bgneal@285 | 8 import urllib2 |
bgneal@285 | 9 import gzip |
bgneal@285 | 10 try: |
bgneal@285 | 11 from cStringIO import StringIO |
bgneal@285 | 12 except ImportError: |
bgneal@285 | 13 from StringIO import StringIO |
bgneal@285 | 14 |
bgneal@285 | 15 |
bgneal@285 | 16 |
bgneal@285 | 17 USER_AGENT = 'gremmies python oembed' |
bgneal@285 | 18 |
bgneal@285 | 19 |
bgneal@908 | 20 def get_oembed(api_endpoint, url, fmt='json', **opts): |
bgneal@285 | 21 """ |
bgneal@285 | 22 Perform the GET request to retrieve the embedded media data from the given |
bgneal@285 | 23 API endpoint for the given URL. Return the result as a Python dictionary. |
bgneal@285 | 24 |
bgneal@908 | 25 fmt specifies the response format, and should be 'json' or 'xml'. |
bgneal@285 | 26 opts are any additional GET options that should be present in the GET |
bgneal@285 | 27 request. |
bgneal@285 | 28 |
bgneal@285 | 29 """ |
bgneal@285 | 30 opts['url'] = url |
bgneal@908 | 31 opts['format'] = fmt |
bgneal@285 | 32 api_url = "%s?%s" % (api_endpoint, urllib.urlencode(opts)) |
bgneal@285 | 33 |
bgneal@285 | 34 headers = { |
bgneal@361 | 35 'User-Agent': USER_AGENT, |
bgneal@285 | 36 'Accept-Encoding': 'gzip', |
bgneal@285 | 37 } |
bgneal@285 | 38 request = urllib2.Request(api_url, headers=headers) |
bgneal@908 | 39 with closing(urllib2.urlopen(request)) as response: |
bgneal@908 | 40 headers = response.info() |
bgneal@908 | 41 result = response.read() |
bgneal@285 | 42 |
bgneal@285 | 43 if headers.get('content-encoding') == 'gzip': |
bgneal@908 | 44 with closing(gzip.GzipFile(fileobj=StringIO(result))) as f: |
bgneal@908 | 45 result = f.read() |
bgneal@285 | 46 |
bgneal@285 | 47 return json.loads(result) |
bgneal@285 | 48 |
bgneal@285 | 49 if __name__ == "__main__": |
bgneal@285 | 50 try: |
bgneal@285 | 51 print get_oembed("http://www.youtube.com/oembed", |
bgneal@907 | 52 "http://www.youtube.com/watch?v=7_IMzJldOf4", |
bgneal@907 | 53 scheme='https') |
bgneal@285 | 54 except urllib2.HTTPError, e: |
bgneal@285 | 55 print e |