Mercurial > public > sg101
comparison gpp/oembed/core.py @ 285:8fd4984d5c3b
This is a first rough commit for #95, adding the ability to embed YouTube videos in forum posts. Some more polish and testing needs to happen at this point. I wanted to get all these changes off my hard drive and into the repository.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Thu, 14 Oct 2010 02:39:35 +0000 |
parents | |
children | 6d6fdc58487c |
comparison
equal
deleted
inserted
replaced
284:df2c81f705a8 | 285:8fd4984d5c3b |
---|---|
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 with gzip.GzipFile(fileobj=StringIO(result)) as f: | |
47 result = f.read() | |
48 | |
49 return json.loads(result) | |
50 | |
51 if __name__ == "__main__": | |
52 try: | |
53 print get_oembed("http://www.youtube.com/oembed", | |
54 #"http://www.youtube.com/watch?v=7_IMzJldOf4") | |
55 "http://www.youtube.com/watch?v=99999999999") | |
56 except urllib2.HTTPError, e: | |
57 print e |