問題描述
goodreads 網站有這個 API 用于訪問用戶的貨架":https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread
The goodreads website has this API for accessing a user's 'shelves:' https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread
它返回 XML.我正在嘗試創建一個 django 項目,該項目在此 API 的書架上顯示書籍.我正在尋找如何(或者是否有更好的方法)來編寫我的視圖,以便我可以將對象傳遞給我的模板.目前,這就是我正在做的事情:
It returns XML. I'm trying to create a django project that shows books on a shelf from this API. I'm looking to find out how (or if there is a better way than) to write my view so I can pass an object to my template. Currently, this is what I'm doing:
import urllib2
def homepage(request):
file = urllib2.urlopen('https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread')
data = file.read()
file.close()
dom = parseString(data)
如果我正確執行此操作,我不完全確定如何操作此對象.我正在關注這個教程.
I'm not entirely sure how to manipulate this object if I'm doing this correctly. I'm following this tutorial.
推薦答案
我會使用 xmltodict
從 XML
數據結構中創建一個 python 字典,并將這個字典傳遞給上下文中的模板:
I'd use xmltodict
to make a python dictionary out of the XML
data structure and pass this dictionary to the template inside the context:
import urllib2
import xmltodict
def homepage(request):
file = urllib2.urlopen('https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread')
data = file.read()
file.close()
data = xmltodict.parse(data)
return render_to_response('my_template.html', {'data': data})
這篇關于將 XML 從 URL 解析為 python 對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!