【问题标题】:Better way to write a JSON file to a DB?将 JSON 文件写入数据库的更好方法?
【发布时间】: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

【问题讨论】:

    标签: python django json embed


    【解决方案1】:

    鉴于有效键在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]
    

    【讨论】:

    • 谢谢!您可能会说,我是编程新手。这很好用。我什至可以将它插入 CouchDB。
    猜你喜欢
    • 1970-01-01
    • 2011-04-12
    • 2014-09-07
    • 2016-01-22
    • 2019-12-20
    • 2018-05-26
    • 1970-01-01
    • 2013-12-17
    • 2019-02-21
    相关资源
    最近更新 更多