comparison oembed/core.py @ 909:90632d090bbc

Merge with upstream.
author Brian Neal <bgneal@gmail.com>
date Mon, 16 Mar 2015 21:03:37 -0500
parents 2181da65c98b
children
comparison
equal deleted inserted replaced
902:4dee923a2f6d 909:90632d090bbc
1 """ 1 """
2 This module contains core functionality for the oembed application. 2 This module contains core functionality for the oembed application.
3 3
4 """ 4 """
5 from contextlib import closing
5 import json 6 import json
6 import urllib 7 import urllib
7 import urllib2 8 import urllib2
8 import gzip 9 import gzip
9 try: 10 try:
14 15
15 16
16 USER_AGENT = 'gremmies python oembed' 17 USER_AGENT = 'gremmies python oembed'
17 18
18 19
19 def get_oembed(api_endpoint, url, format='json', **opts): 20 def get_oembed(api_endpoint, url, fmt='json', **opts):
20 """ 21 """
21 Perform the GET request to retrieve the embedded media data from the given 22 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 API endpoint for the given URL. Return the result as a Python dictionary.
23 24
24 format specifies the response format, and should be 'json' or 'xml'. 25 fmt 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 opts are any additional GET options that should be present in the GET
26 request. 27 request.
27 28
28 """ 29 """
29 opts['url'] = url 30 opts['url'] = url
30 opts['format'] = format 31 opts['format'] = fmt
31 api_url = "%s?%s" % (api_endpoint, urllib.urlencode(opts)) 32 api_url = "%s?%s" % (api_endpoint, urllib.urlencode(opts))
32 33
33 headers = { 34 headers = {
34 'User-Agent': USER_AGENT, 35 'User-Agent': USER_AGENT,
35 'Accept-Encoding': 'gzip', 36 'Accept-Encoding': 'gzip',
36 } 37 }
37 request = urllib2.Request(api_url, headers=headers) 38 request = urllib2.Request(api_url, headers=headers)
38 39 with closing(urllib2.urlopen(request)) as response:
39 opener = urllib2.build_opener() 40 headers = response.info()
40 f = opener.open(request) 41 result = response.read()
41 headers = f.info()
42 result = f.read()
43 f.close()
44 42
45 if headers.get('content-encoding') == 'gzip': 43 if headers.get('content-encoding') == 'gzip':
46 f = gzip.GzipFile(fileobj=StringIO(result)) 44 with closing(gzip.GzipFile(fileobj=StringIO(result))) as f:
47 result = f.read() 45 result = f.read()
48 f.close()
49 46
50 return json.loads(result) 47 return json.loads(result)
51 48
52 if __name__ == "__main__": 49 if __name__ == "__main__":
53 try: 50 try:
54 print get_oembed("http://www.youtube.com/oembed", 51 print get_oembed("http://www.youtube.com/oembed",
55 "http://www.youtube.com/watch?v=7_IMzJldOf4") 52 "http://www.youtube.com/watch?v=7_IMzJldOf4",
53 scheme='https')
56 except urllib2.HTTPError, e: 54 except urllib2.HTTPError, e:
57 print e 55 print e