Created
December 14, 2017 02:41
-
-
Save kwatog/8d178f04f2af7cb58cd67017f361264b to your computer and use it in GitHub Desktop.
Django oEmbed YouTube and Vimeo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import template | |
from django.template.defaultfilters import stringfilter | |
from mezzanine.blog.models import BlogPost | |
import json | |
import re | |
import requests | |
from urllib.parse import quote_plus | |
register = template.Library() | |
@register.filter(is_safe=True) | |
@stringfilter | |
def oembed(content): | |
patterns = ( | |
('http://www.youtube.com/oembed?format=json&url=', | |
re.compile("https?:\/\/(www\.)?youtu(\.be|be\.com\/watch)[\?=\w.@+-]+")), | |
('https://vimeo.com/api/oembed.json?url=', | |
re.compile("https?:\/\/(www\.)?vimeo\.com\/[\d]+")) | |
) | |
for p in patterns: | |
for match in re.finditer(p[1], content): | |
match_text = match.group() | |
url = "%s%s"%(p[0], quote_plus(match_text)) | |
resp = requests.get(url) | |
if resp.status_code == requests.codes.ok: | |
data = json.loads(resp.text) | |
replace_text = "<div class=\"%s\">%s</div>"%(data['type'], data['html']) | |
content = content.replace(match_text, replace_text) | |
return content |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment