将JSON文件写入数据库的更好方法是什么?

时间:2011-04-19 20:30:02

标签: python django json embed

以下是该方案: - 我正在使用embed.ly的oembed服务来提取有关用户提交链接的元数据(有关该服务的更多信息:http://api.embed.ly/docs/oembed) - 我使用此内容生成我网站上的内容预览 - 当我提交一个URL来嵌入时,该服务会给我一个包含元数据的JSON文件 - 我想将此内容写入数据库,因为用户将在我的网站上反复访问此信息 - 我正在使用Django

我有scritp工作。以下是我的代码。我不喜欢它是它硬编码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

1 个答案:

答案 0 :(得分:0)

鉴于有效密钥在embedly's repsonse documentation中定义,您可以通过在一个位置指定支持的响应密钥和翻译列表来使代码更易于维护,从而减少冗余代码的数量。

例如:

# embed.ly keys which map 1:1 with your database record keys
RESPONSE_KEYS = set([
    'provider_url', 'description', 'title', 'author_name', 'thumbnail_url',
    'thumbnail_width', 'thumbnail_height', 'author_url'
    ])

# mapping from embed.ly's key name to your database record key
KEY_MAP = {
    'url': 'content_url',
    'width': 'width_px',
    'height': 'height_px',
    'type': 'url_type'
    }

url_return = get_oembed(content_url)
record = ContentQueue(submitted_url=content_url)
record.version = 1

# iterate over the response keys and add them to the record
for key_name in url_return.iterkeys():
    key = key_name if key_name in RESPONSE_KEYS else KEY_MAP.get(key_name)
    if key:
        record[key] = url_return[key_name]