comparison oembed/core.py @ 581:ee87ea74d46b

For Django 1.4, rearranged project structure for new manage.py.
author Brian Neal <bgneal@gmail.com>
date Sat, 05 May 2012 17:10:48 -0500
parents gpp/oembed/core.py@6d6fdc58487c
children 89b240fe9297
comparison
equal deleted inserted replaced
580:c525f3e0b5d0 581:ee87ea74d46b
1 """
2 This module contains core functionality for the oembed application.
3 """
4 from __future__ import with_statement
5 import urllib
6 import urllib2
7 import gzip
8 try:
9 from cStringIO import StringIO
10 except ImportError:
11 from StringIO import StringIO
12
13 import django.utils.simplejson as json
14
15
16 USER_AGENT = 'gremmies python oembed'
17
18
19 def get_oembed(api_endpoint, url, format='json', **opts):
20 """
21 Perform the GET request to retrieve the embedded media data from the given
22 API endpoint for the given URL. Return the result as a Python dictionary.
23
24 format specifies the response format, and should be 'json' or 'xml'.
25 opts are any additional GET options that should be present in the GET
26 request.
27
28 """
29 opts['url'] = url
30 opts['format'] = format
31 api_url = "%s?%s" % (api_endpoint, urllib.urlencode(opts))
32
33 headers = {
34 'User-Agent': USER_AGENT,
35 'Accept-Encoding': 'gzip',
36 }
37 request = urllib2.Request(api_url, headers=headers)
38
39 opener = urllib2.build_opener()
40 f = opener.open(request)
41 headers = f.info()
42 result = f.read()
43 f.close()
44
45 if headers.get('content-encoding') == 'gzip':
46 f = gzip.GzipFile(fileobj=StringIO(result))
47 result = f.read()
48 f.close()
49
50 return json.loads(result)
51
52 if __name__ == "__main__":
53 try:
54 print get_oembed("http://www.youtube.com/oembed",
55 "http://www.youtube.com/watch?v=7_IMzJldOf4")
56 except urllib2.HTTPError, e:
57 print e