本文整理汇总了Python中embedly.Embedly类的典型用法代码示例。如果您正苦于以下问题:Python Embedly类的具体用法?Python Embedly怎么用?Python Embedly使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Embedly类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: replace
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)
示例2: _add_embedly_data
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))
示例3: replace
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)
示例4: embedly_link
def embedly_link(URL):
#Takes a URL, returns a populated Link object
#Returns "error" if Embedly API fails
client = Embedly(embedly_key)
response = client.extract(URL)
try:
#Get link information from Embedly
headline = response['title']
URL = clean_url(response['url'])
summary = response['description']
source = response['provider_name']
path = page_path(headline)
keywords_response = response['keywords']
keyword1 = str(keywords_response[0]['name'])
keyword2 = str(keywords_response[1]['name'])
keyword3 = str(keywords_response[2]['name'])
keyword4 = str(keywords_response[3]['name'])
keyword5 = str(keywords_response[4]['name'])
#Create Link object with info from Embedly
link = Link(headline = headline, url = URL, source = source, summary = summary,
path = path, keyword1 = keyword1, keyword2 = keyword2, keyword3 = keyword3,
keyword4 = keyword4, keyword5 = keyword5, votes = 0)
return link
except:
return "error"
示例5: detect_embedded_content
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
示例6: create_embed
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)
示例7: get_oembed_data
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
示例8: cache_embed
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")
示例9: get_embed_object
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")
示例10: get_info_if_active
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.
示例11: embedly
def embedly(url):
try:
client = Embedly(settings.EMBEDLY_KEY)
obj = client.oembed(url)
except:
return None
if obj.type == "photo":
return '<a href="%s" class="embed"><img src="%s"></a>' % (
obj.url, obj.url)
return None
示例12: get_list_from_embedly
def get_list_from_embedly(bitly_url_links,KEY):
client = Embedly(KEY)
data_dict = dict()
temp_dict = dict()
for p,link in enumerate(bitly_url_links):
link = client.oembed(link)
temp_dict['title'] = link['title']
temp_dict['url'] = link['url']
temp_dict['thumbnail_url'] = link['thumbnail_url']
temp_dict['thumbnail_width'] = link['thumbnail_width']
temp_dict['description'] = link['description']
data_dict[p] = temp_dict
return data_dict
示例13: get_article
def get_article():
url = request.args.get('url')
client = Embedly('f2f84ff5013b443ab711b204590d9aa2')
result = client.extract(url)
article = {}
article["url"] = result["url"]
article["headline"] = result["title"]
article["description"] = result["description"]
article["content"] = result["content"]
response = make_response(json.dumps(article, indent=4))
response.headers['Access-Control-Allow-Origin'] = "*"
return response
示例14: set_media
def set_media():
link = request.form.get('value')
contribution = get_contribution(get_referer())
client = Embedly('a54233f91473419f9a947e1300f27f9b')
obj = client.oembed(link)
meta = obj.__dict__
media = {
'type' : request.form.get('type'),
'url' : meta.get('url'),
'meta' : meta
}
contrib = update_media(media, get_referer())
return dumps(contrib)
示例15: get_links
def get_links(text):
url_regex = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[[email protected]&+]|[!*\(\),]|'
'(?:%[0-9a-fA-F][0-9a-fA-F]))+')
urls = url_regex.findall(text)
embedly = []
client = Embedly(app.config['EMBEDLY_KEY'])
for url in urls:
embedly.append(client.oembed(url))
return embedly