本文整理汇总了Python中embedly.Embedly.oembed方法的典型用法代码示例。如果您正苦于以下问题:Python Embedly.oembed方法的具体用法?Python Embedly.oembed怎么用?Python Embedly.oembed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类embedly.Embedly
的用法示例。
在下文中一共展示了Embedly.oembed方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_oembed_data
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def get_oembed_data(context_var, maxwidth=None, maxheight=None):
'''
A custom templatetag that returns an object representing
all oembed data for a given url found in a context variable
Usage:
{% load embed_filters %}
{% with context_var="Check out my cool photo: http://www.flickr.com/photos/visualpanic/233508614/" %}
{{ context_var }}
{% get_oembed_data context_var maxwidth=400 as oembed %}
<div class="embed-data">
{{oembed.title}} <br />
{{oembed.description}} <br />
{{oembed.html}} <br />
</div>
{% endwith %}
Uses the Embedly API to get oembed data. Always look to the db/cache first,
and then fall back to the Embedly API for speed
(at the cost of accuracy & updated urls).
'''
url = _get_url_from_context_variable(context_var)
if not url:
return {}
#if maxwidth or maxheight is None, the unique_together constraint does not work
#for now, just filter and check first element instead of using objects.get
try:
saved_embed = SavedEmbed.objects.filter(url=url, maxwidth=maxwidth, maxheight=maxheight)[0]
except IndexError:
client = Embedly(key=settings.EMBEDLY_KEY, user_agent=USER_AGENT)
try:
if maxwidth and maxheight:
oembed = client.oembed(url, maxwidth=maxwidth, maxheight=maxheight)
elif maxwidth:
oembed = client.oembed(url, maxwidth=maxwidth)
elif maxheight:
oembed = client.oembed(url, maxheight=maxheight)
else:
oembed = client.oembed(url)
except: #TODO: don't catch all exceptions
return {}
if oembed.error:
return {}
saved_embed, created = SavedEmbed.objects.get_or_create(
url=url,
maxwidth=maxwidth,
maxheight=maxheight,
defaults={
'type': oembed.type,
'oembed_data': oembed.data
})
return saved_embed.oembed_data
示例2: cache_embed
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def cache_embed(request):
if not request.POST:
return HttpResponseBadRequest("cache_embed requires POST")
url = request.POST.get('url')
if not url:
return HttpResponseBadRequest("POST a url, and I'll happily cache it")
maxwidth = request.POST.get('maxwidth')
#try memcache first
key = make_cache_key(url, maxwidth)
cached_response = cache.get(key)
if cached_response and type(cached_response) == type(dict()):
cached_response['cache'] = 'memcache'
return HttpResponse(json.dumps(cached_response), mimetype="application/json")
#then the database
try:
saved = SavedEmbed.objects.get(url=url, maxwidth=maxwidth)
response = saved.response
response['html'] = saved.html
response['cache'] = 'database'
cache.set(key, response) #and save it to memcache
return HttpResponse(json.dumps(response), mimetype="application/json")
except SavedEmbed.DoesNotExist:
pass
#if we've never seen it before, call the embedly API
client = Embedly(key=settings.EMBEDLY_KEY, user_agent=USER_AGENT)
if maxwidth:
oembed = client.oembed(url, maxwidth=maxwidth)
else:
oembed = client.oembed(url)
if oembed.error:
return HttpResponseServerError('Error embedding %s.\n %s' % (url,oembed.error))
#save result to database
row, created = SavedEmbed.objects.get_or_create(url=url, maxwidth=maxwidth,
defaults={'type': oembed.type})
row.provider_name = oembed.provider_name
row.response = json.dumps(oembed.data)
if oembed.type == 'photo':
html = '<img src="%s" width="%s" height="%s" />' % (oembed.url,
oembed.width, oembed.height)
else:
html = oembed.html
if html:
row.html = html
row.last_updated = datetime.now()
row.save()
#and to memcache
cache.set(key, row.response, 86400)
response = row.response
response['html'] = row.html #overwrite for custom oembed types
response['cache'] = "none"
return HttpResponse(json.dumps(response), mimetype="application/json")
示例3: embed_replace
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def embed_replace(match, maxwidth=None):
url = match.group(1)
key = make_cache_key(url, maxwidth)
cached_html = cache.get(key)
if cached_html:
return cached_html
# call embedly API
client = Embedly(key=settings.EMBEDLY_KEY, user_agent=USER_AGENT)
if maxwidth:
oembed = client.oembed(url, maxwidth=maxwidth)
else:
oembed = client.oembed(url)
# check database
if oembed.error:
try:
html = SavedEmbed.objects.get(url=url, maxwidth=maxwidth).html
cache.set(key, html)
return html
except SavedEmbed.DoesNotExist:
err_code = (oembed.data['error_code']
if 'error_code' in oembed.data else 'Unknown')
LOG.warn('Error fetching %s (%s)', url, err_code)
return url
# save result to database
row, created = SavedEmbed.objects.get_or_create(url=url, maxwidth=maxwidth,
defaults={'type': oembed.type})
if oembed.type == 'photo':
html = '<img src="%s" ' % oembed.url
if maxwidth:
html += 'width="%s" />' % maxwidth
else:
html += 'width="%s" height="%s" />' % (oembed.width, oembed.height)
else:
html = oembed.html
if html:
row.html = html
row.last_updated = datetime.now()
row.save()
# set cache
cache.set(key, html, 86400)
return html
示例4: embedly
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def embedly(url, max_width=None, key=None):
from embedly import Embedly
# Get embedly key
if key is None:
try:
key = settings.WAGTAILEMBEDS_EMBEDLY_KEY
except AttributeError:
key = settings.EMBEDLY_KEY
warnings.warn(
"EMBEDLY_KEY is now deprecated. Use WAGTAILEMBEDS_EMBEDLY_KEY instead",
RemovedInWagtail14Warning)
# Get embedly client
client = Embedly(key=key)
# Call embedly
if max_width is not None:
oembed = client.oembed(url, maxwidth=max_width, better=False)
else:
oembed = client.oembed(url, better=False)
# Check for error
if oembed.get('error'):
if oembed['error_code'] in [401, 403]:
raise AccessDeniedEmbedlyException
elif oembed['error_code'] == 404:
raise EmbedNotFoundException
else:
raise EmbedlyException
# Convert photos into HTML
if oembed['type'] == 'photo':
html = '<img src="%s" />' % (oembed['url'], )
else:
html = oembed.get('html')
# Return embed as a dict
return {
'title': oembed['title'] if 'title' in oembed else '',
'author_name': oembed['author_name'] if 'author_name' in oembed else '',
'provider_name': oembed['provider_name'] if 'provider_name' in oembed else '',
'type': oembed['type'],
'thumbnail_url': oembed.get('thumbnail_url'),
'width': oembed.get('width'),
'height': oembed.get('height'),
'html': html,
}
示例5: replace
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def replace(match):
url = match.group('url')
try:
url_validate(url)
if match.group('kind') == 'externaltask':
return '<button class="external-task" data-url="%s">%s</button>' % (
url, # TODO: Should we escape/encode this somehow?
_('Start This Task')
)
expiration_date = datetime.now() - settings.EMBEDLY_CACHE_EXPIRES
embedded_urls = EmbeddedUrl.objects.filter(original_url=url,
created_on__gte=expiration_date).order_by('-created_on')
embedded_url = None
if embedded_urls.exists():
embedded_url = embedded_urls[0]
else:
embedly_key = getattr(settings, 'EMBEDLY_KEY', False)
if embedly_key:
client = Embedly(embedly_key)
obj = client.oembed(url, maxwidth=460)
embedded_url = EmbeddedUrl(original_url=obj.original_url,
html=(obj.html or ''), extra_data=obj.dict)
embedded_url.save()
if embedded_url and embedded_url.html:
return embedded_url.html
except ValidationError:
return '[embed:Invalid Url]'
return DEFAULT_EMBED % (url, url)
示例6: _add_embedly_data
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def _add_embedly_data(instance):
import json
from embedly import Embedly
from main.api2 import APIException
# for security, we can't let the client set embedly_data
assert instance.original_url
assert not instance.embedly_data
client = Embedly(settings.EMBEDLY_KEY)
obj = client.oembed(instance.original_url,
autoplay=False,
maxwidth=600,
# Fix overlay issues with flash under chrome/linux:
wmode='transparent'
)
if obj.invalid:
raise APIException('The submitted link is invalid')
elif obj.type is 'error':
raise APIException('Embedly error', obj.error_code)
elif not obj.html:
raise APIException('No embed html received')
else:
assert obj.provider_name.lower() in settings.ALLOWED_EMBEDLY_PROVIDERS
instance.width = obj.width
instance.height = obj.height
instance.embedly_data = json.dumps(dict(obj))
示例7: replace
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def replace(match):
url = match.group('url')
kind = match.group('kind')
external_task = (match.group('kind') == 'externaltask')
try:
url_validate(url)
except ValidationError:
return '[%s:Invalid Url]' % kind
for prefix in settings.P2PU_EMBEDS:
if url.startswith(prefix):
return render_to_string('richtext/_p2pu_embed.html', {'url': url})
if not external_task:
expiration_date = datetime.now() - settings.EMBEDLY_CACHE_EXPIRES
embedded_urls = EmbeddedUrl.objects.filter(original_url=url,
created_on__gte=expiration_date).order_by('-created_on')
embedded_url = None
if embedded_urls.exists():
embedded_url = embedded_urls[0]
else:
embedly_key = getattr(settings, 'EMBEDLY_KEY', False)
if embedly_key:
client = Embedly(embedly_key)
obj = client.oembed(url, maxwidth=460)
embedded_url = EmbeddedUrl(original_url=obj.original_url,
html=(obj.html or ''), extra_data=obj.dict)
embedded_url.save()
if embedded_url and embedded_url.html:
return embedded_url.html
context = {'url': url, 'external_task': external_task}
return render_to_string('richtext/_external_link.html', context)
示例8: get_embed_embedly
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def get_embed_embedly(url, max_width=None):
# Check database
try:
return Embed.objects.get(url=url, max_width=max_width)
except Embed.DoesNotExist:
pass
try:
# Call embedly API
client = Embedly(key=settings.EMBEDLY_KEY)
except AttributeError:
return None
if max_width is not None:
oembed = client.oembed(url, maxwidth=max_width, better=False)
else:
oembed = client.oembed(url, better=False)
# Check for error
if oembed.get('error'):
return None
# Save result to database
row, created = Embed.objects.get_or_create(
url=url,
max_width=max_width,
defaults={
'type': oembed['type'],
'title': oembed['title'],
'thumbnail_url': oembed.get('thumbnail_url'),
'width': oembed.get('width'),
'height': oembed.get('height')
}
)
if oembed['type'] == 'photo':
html = '<img src="%s" />' % (oembed['url'], )
else:
html = oembed.get('html')
if html:
row.html = html
row.last_updated = datetime.now()
row.save()
# Return new embed
return row
示例9: create_embed
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def create_embed(self, options):
embed = Embedly(settings.EMBEDLY_API_KEY)
obj = embed.oembed(options['url'], width=options['width'], height=options['height'])
el = etree.Element('div')
el.set('class', 'post-embed')
el.append(html.fromstring(obj.html))
return html.tostring(el)
示例10: detect_embedded_content
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def detect_embedded_content(text):
results = []
client = Embedly(key=EMBEDLY_KEY, user_agent=USER_AGENT)
for url in re.findall(EMBED_REGEX, text):
results.append(client.oembed(url))
return results
示例11: get_embed_object
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def get_embed_object(url):
if not settings.EMBEDLY_KEY:
raise ImproperlyConfigured("You have not specified an Embedly key in your settings file.")
try:
client = Embedly(settings.EMBEDLY_KEY)
resp = client.oembed(url, maxwidth=settings.EMBED_MAX_WIDTH, maxheight=settings.EMBED_MAX_HEIGHT)
except Exception, e:
raise EmbedlyException("There was an issue with your embed URL. Please check that it is valid and try again")
示例12: embed_replace
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def embed_replace(match, maxwidth=None):
url = match.group(1)
key = make_cache_key(url, maxwidth)
cached_html = cache.get(key)
if cached_html:
return cached_html
# call embedly API
client = Embedly(key=settings.EMBEDLY_KEY, user_agent=USER_AGENT)
if maxwidth:
oembed = client.oembed(url, maxwidth=maxwidth)
else:
oembed = client.oembed(url)
# check database
if oembed.error:
try:
html = SavedEmbed.objects.get(url=url, maxwidth=maxwidth).html
cache.set(key, html)
return html
except SavedEmbed.DoesNotExist:
return "Error embedding %s" % url
# save result to database
row, created = SavedEmbed.objects.get_or_create(url=url, maxwidth=maxwidth, defaults={"type": oembed.type})
if oembed.type == "photo":
html = u'<img src="%s" width="%s" height="%s" />' % (oembed.url, oembed.width, oembed.height)
elif oembed.type == "link":
html = u'Link to: <a href="{url}">{title}</a>'.format(url=oembed.url, title=oembed.title)
else:
html = oembed.html
if html:
row.html = html
row.last_updated = datetime.now()
row.save()
# set cache
cache.set(key, html, 86400)
return html
示例13: find_embed
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def find_embed(self, url, max_width=None, key=None):
from embedly import Embedly
# Get embedly key
if key is None:
key = self.get_key()
# Get embedly client
client = Embedly(key=key)
# Call embedly
if max_width is not None:
oembed = client.oembed(url, maxwidth=max_width, better=False)
else:
oembed = client.oembed(url, better=False)
# Check for error
if oembed.get('error'):
if oembed['error_code'] in [401, 403]:
raise AccessDeniedEmbedlyException
elif oembed['error_code'] == 404:
raise EmbedNotFoundException
else:
raise EmbedlyException
# Convert photos into HTML
if oembed['type'] == 'photo':
html = '<img src="%s" />' % (oembed['url'], )
else:
html = oembed.get('html')
# Return embed as a dict
return {
'title': oembed['title'] if 'title' in oembed else '',
'author_name': oembed['author_name'] if 'author_name' in oembed else '',
'provider_name': oembed['provider_name'] if 'provider_name' in oembed else '',
'type': oembed['type'],
'thumbnail_url': oembed.get('thumbnail_url'),
'width': oembed.get('width'),
'height': oembed.get('height'),
'html': html,
}
示例14: embedly
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def embedly(url, max_width=None, key=None):
from embedly import Embedly
# Get embedly key
if key is None:
key = settings.EMBEDLY_KEY
# Get embedly client
client = Embedly(key=key)
# Call embedly
if max_width is not None:
oembed = client.oembed(url, maxwidth=max_width, better=False)
else:
oembed = client.oembed(url, better=False)
# Check for error
if oembed.get("error"):
if oembed["error_code"] in [401, 403]:
raise AccessDeniedEmbedlyException
elif oembed["error_code"] == 404:
raise EmbedNotFoundException
else:
raise EmbedlyException
# Convert photos into HTML
if oembed["type"] == "photo":
html = '<img src="%s" />' % (oembed["url"],)
else:
html = oembed.get("html")
# Return embed as a dict
return {
"title": oembed["title"] if "title" in oembed else "",
"author_name": oembed["author_name"] if "author_name" in oembed else "",
"provider_name": oembed["provider_name"] if "provider_name" in oembed else "",
"type": oembed["type"],
"thumbnail_url": oembed.get("thumbnail_url"),
"width": oembed.get("width"),
"height": oembed.get("height"),
"html": html,
}
示例15: get_info_if_active
# 需要导入模块: from embedly import Embedly [as 别名]
# 或者: from embedly.Embedly import oembed [as 别名]
def get_info_if_active(url):
oembed = None
if not ACTIVE:
return oembed
client = Embedly(settings.EMBEDLY_KEY)
try:
oe = client.oembed(url, maxwidth=None if not hasattr(settings,'EMBEDLY_MAXWIDTH') else settings.EMBEDLY_MAXWIDTH)
if not oe.error:
oembed = oe
except httplib2.ServerNotFoundError, e:
pass # Can't connect to server.