2011-04-19 2 views
1

여기에 시나리오의 : -I 사용이 콘텐츠를 내 사이트 - 언제 콘텐츠의 미리보기를 생성 : - 난 사용자가 제출 링크 (http://api.embed.ly/docs/oembed 해당 서비스에 대한 자세한 정보)에 대한 메타 데이터를 끌어 embed.ly에서 oEmbed있어 서비스를 사용하여 나는 URL을 제출하여 embed.ly 서비스는 나에게 메타 데이터가 들어있는 JSON 파일을 돌려 준다. - 사용자가 내 웹 사이트에서 반복적으로이 정보에 액세스 할 것이므로이 정보를 데이터베이스에 기록하고 싶다. - 장고를 사용 중이다.JSON 파일을 DB에 작성하는 더 나은 방법은 무엇입니까?

나는 scritp 작동합니다. 아래는 제 코드입니다. 내가 싫어하는 점은 JSON 파일에있는 키를 하드 코딩한다는 것입니다. 키가 변경되거나 주어진 쿼리에 키가 제공되지 않으면 상황이 깨집니다. 나중의 문제를 수정할 수는 있지만 누락 된 데이터 또는 키 변경을 허용하는 다른 접근 방법을 가진 사람이 있는지 궁금해졌습니다. 여기

이 (embed.ly에서이있어) JSON 파일 생성 파이썬 코드 :

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 

답변

0

감안할 : 여기

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()) 

을 그리고 것은 DB에이 글을 내 코드입니다 유효한 키가 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] 
+0

감사합니다! 당신이 말할 수 있듯이, 나는 프로그래밍에 초보자입니다. 이것은 훌륭하게 작동했습니다. 나는 이것을 심지어 CouchDB에 연결할 수있었습니다. – tabdon

관련 문제