我学习Kivy。我有带CRUD功能的Django应用程序(Books Library)和API(Tastypie)。
如何使用我所有图书的列表来查看“算法”构建应用程序?用于列出的组件以及如何从API检索数据并显示它们?
mysite.com/api/books/?format=json
JSON:
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 8}, "objects": [{"title": "Kivy book", "description": "Cool book", "id": 1, "page_count": 155}]}
任何人都可以提供这个简单示例的代码吗?
答案 0 :(得分:1)
以下是我正在努力实现的一个例子。它基于最简单的ListView example。请注意,我从您提供的示例中创建了扩展JSON版本。此外,当您想要使用URL时,您必须替换2个注释行。加载json的方法是load
(对于io输入)而不是loads
(对于字符串输入)。
from kivy.uix.listview import ListView
from kivy.uix.gridlayout import GridLayout
import json
import urllib2
class MainView(GridLayout):
def __init__(self, **kwargs):
kwargs['cols'] = 2
super(MainView, self).__init__(**kwargs)
the_string_json = '{"meta": {"previous": null, "total_count": 8, "offset": 0, "limit": 20, "next": null}, "objects": [{"id": 1, "page_count": 155, "description": "Cool book", "title": "Kivy book 1"}, {"id": 1, "page_count": 155, "description": "Cool book", "title": "Kivy book 2"}, {"id": 1, "page_count": 155, "description": "Cool book", "title": "Kivy book 3"}]}'
the_dict = json.loads(the_string_json)
# Substitute the previous two lines for this ones:
# the_io_json = urllib2.urlopen('mysite.com/api/books/?format=json')
# the_dict = json.load(the_io_json)
list_view = ListView(
item_strings=[book['title'] for book in the_dict['objects']])
self.add_widget(list_view)
if __name__ == '__main__':
from kivy.base import runTouchApp
runTouchApp(MainView(width=800))