Skip to content

Instantly share code, notes, and snippets.

@kwatog
Created December 14, 2017 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwatog/8d178f04f2af7cb58cd67017f361264b to your computer and use it in GitHub Desktop.
Save kwatog/8d178f04f2af7cb58cd67017f361264b to your computer and use it in GitHub Desktop.
Django oEmbed YouTube and Vimeo
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