【发布时间】:2011-08-09 00:02:43
【问题描述】:
这是场景: -我正在使用 embed.ly 的 oembed 服务来提取有关用户提交的链接的元数据(有关该服务的更多信息:http://api.embed.ly/docs/oembed) -我使用此内容在我的网站上生成内容预览 - 当我向 embed.ly 提交 URL 时,服务会返回一个包含元数据的 JSON 文件 -我想将其写入数据库,因为用户将在我的网站上重复访问此信息 -我正在使用 Django
我有脚本工作。下面是我的代码。我不喜欢它的是它对 JSON 文件中的密钥进行硬编码。如果键发生变化,或者没有在给定的查询中提供,那么事情就会中断。我可以解决后面的问题,但很好奇是否有人有不同的方法可以容忍丢失数据或更改密钥。
这是生成 JSON 文件的 Python 代码(从 embed.ly 获得):
def submit_content(request):
import urllib
import urllib2
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
raise ImportError("Need a json decoder")
ACCEPTED_ARGS = ['maxwidth', 'maxheight', 'format']
def get_oembed(url, **kwargs):
"""
Example Embedly oEmbed Function
"""
api_url = 'http://api.embed.ly/1/oembed?'
params = {'url':url }
for key, value in kwargs.items():
if key not in ACCEPTED_ARGS:
raise ValueError("Invalid Argument %s" % key)
params[key] = value
oembed_call = "%s%s" % (api_url, urllib.urlencode(params))
return json.loads(urllib2.urlopen(oembed_call).read())
这是我将其写入数据库的代码:
if request.method == 'POST':
form = SubmitContent(request.POST)
if form.is_valid():
user = request.user
content_url = form.cleaned_data['content_url']
url_return = get_oembed(content_url)
recordSave = ContentQueue(submitted_url=content_url)
for key in url_return:
if key == 'provider_url':
recordSave.provider_url = url_return[key]
if key == 'description':
recordSave.description = url_return[key]
if key == 'title':
recordSave.title = url_return[key]
if key == 'url':
recordSave.content_url = url_return[key]
if key == 'author_name':
recordSave.author_name = url_return[key]
if key == 'height':
recordSave.height_px = url_return[key]
if key == 'width':
recordSave.width_px = url_return[key]
if key == 'thumbnail_url':
recordSave.thumbnail_url = url_return[key]
if key == 'thumbnail_width':
recordSave.thumbnail_width = url_return[key]
if key == 'version':
recordSave.version = 1
if key == 'provider_name':
recordSave.provider_name = url_return[key]
if key == 'cache_age':
recordSave.cache_age = url_return[key]
if key == 'type':
recordSave.url_type = url_return[key]
if key == 'thumbnail_height':
recordSave.thumbnail_height = url_return[key]
if key == 'author_url':
recordSave.author_url = url_return[key]
recordSave.user = user
【问题讨论】: