diff --git a/oembed/core.py b/oembed/core.py index ad96721..1219524 100644 --- a/oembed/core.py +++ b/oembed/core.py @@ -1,15 +1,12 @@ import re import urllib2 import gzip +import json from heapq import heappush, heappop try: from cStringIO import StringIO except ImportError: from StringIO import StringIO -try: - import simplejson -except ImportError: - from django.utils import simplejson from django.conf import settings from django.utils.safestring import mark_safe from oembed.models import ProviderRule, StoredOEmbed @@ -62,10 +59,10 @@ def match_compare(x, y): return x.start() - y.start() prev_end = 0 iter_dict = dict((r, r.finditer(text)) for r in regex_list) - + # a heapq containing matches matches = [] - + # bootstrap the search with the first hit for each iterator for regex, iterator in iter_dict.items(): try: @@ -73,7 +70,7 @@ def match_compare(x, y): heappush(matches, (match.start(), match)) except StopIteration: iter_dict.pop(regex) - + # process matches, revisiting each iterator from which a match is used while matches: # get the earliest match @@ -102,12 +99,12 @@ def replace(text, max_width=MAX_WIDTH, max_height=MAX_HEIGHT): """ Scans a block of text, replacing anything matched by a ``ProviderRule`` pattern with an OEmbed html snippet, if possible. - + Templates should be stored at oembed/{format}.html, so for example: - + oembed/video.html - - These templates are passed a context variable, ``response``, which is a + + These templates are passed a context variable, ``response``, which is a dictionary representation of the response. """ rules = list(ProviderRule.objects.all()) @@ -137,7 +134,7 @@ def replace(text, max_width=MAX_WIDTH, max_height=MAX_HEIGHT): if to_append: parts.append(to_append) index += 1 - # Now we fetch a list of all stored patterns, and put it in a dictionary + # Now we fetch a list of all stored patterns, and put it in a dictionary # mapping the URL to to the stored model instance. for stored_embed in StoredOEmbed.objects.filter(match__in=urls, max_width=max_width, max_height = max_height): stored[stored_embed.match] = stored_embed @@ -156,12 +153,12 @@ def replace(text, max_width=MAX_WIDTH, max_height=MAX_HEIGHT): rule.endpoint, part, max_width, max_height, FORMAT ) # Fetch the link and parse the JSON. - resp = simplejson.loads(fetch(url)) - + resp = json.loads(fetch(url)) + # link types that don't have html elements aren't dealt with right now. if resp['type'] == 'link' and 'html' not in resp: raise ValueError - + # Depending on the embed type, grab the associated template and # pass it the parsed JSON response as context. replacement = render_to_string('oembed/%s.html' % resp['type'], {'response': resp})