看來你正試圖用Django製作一個API。您可以閱讀更多關於REST API的here。基本的想法是,你的網站將有一組命令鏈接/ URL - 每個鏈接將執行一些操作(更新數據庫等),只是返回一些信息(最常見的是JSON - 例如從數據庫返回一個對象) ,或者將兩者兼而有之。
你將不得不做的是列出所有可能的API命令將要處理的命令。這將包括檢索,插入,更新和刪除數據的所有命令。
對於此示例,我們假設應用程序的唯一工作是管理商店中的商品。這是一個非常簡化的演示,但它應該得到重點。
這裏是一個Django模型(內Store
Django應用程序):
class Item(models.Model):
name = models.CharField(max_length=255)
price = models.IntegerField() # assume the price is always int
quantity = models.IntegerField()
那麼接下來讓我們假設爲API是可能的命令:
- 獲取有關特定項目的信息
- 獲取信息關於所有項目
- 特定商品的更新信息
- 刪除特定項目
- 添加物品到存儲
URL結構中的所有命令
urlpatterns = patterns('',
# will be used for getting, updating, and removing an item
url(r'^item/(?P<item_id>\d+)/$', "item"),
# will be used to get info about all items
url(r'^item/all/$', "item_all"),
# will be used to create new item
url(r'^item/new/$', "item_new"),
)
獲取信息有關的所有項目
爲了從django獲取信息信息,django序列化函數非常有用。 Here是一個django文檔。
#views.py
from django.core import serializers
import json
def item_all(request):
items = Item.objects.all()
data = serializers.serialize("json", items)
return HttpResponse(data, mimetype="application/json")
這將完成是返回一個JSON陣列,像這樣所有的項目:
[
{
pk: 1,
model: "store.item",
fields: {
name: "some_name",
price: 20,
quantity: 1000
}
},
// more items here
]
添加新項
對於這個您的Android應用程序將有發送一個JSON對象給Django。
JSON對象:
{ data:
{
name: "some_name",
price: 40,
quantity: 2000
}
}
所以,現在你的Django應用程序必須分析來自請求的信息,以創建一個新項目:
#views.py
def item_new(request):
# the request type has to be POST
if request.method != "POST":
return HttpResponseBadRequest("Request has to be of type POST")
postdata = request.POST[u"data"]
postdata = json.loads(postdata)
item = Item()
item.name = postdata["name"]
item.price = postdata["price"]
item.quantity = postdata["quantity"]
item.save()
data = serializers.serialize("json", [item])
return HttpResponse(data, mimetype="application/json")
一些注意事項:
注使用POST請求類型。這在REST API中非常重要。基本上取決於請求類型,將執行不同的操作。在接下來的觀點中這將更加生動。
獲取,更新和刪除
#views.py
def item(request, item_id):
item = get_object_or_404(Item, pk=item_id)
if request.method == "GET":
data = serializers.serialize("json", [item])
return HttpResponse(data, mimetype="application/json")
elif request.method == "POST":
postdata = request.POST[u"data"]
postdata = json.loads(postdata)
item.name = postdata["name"]
item.price = postdata["price"]
item.quantity = postdata["quantity"]
item.save()
data = json.dumps(True)
return HttpResponse(data, mimetype="application/json")
elif request.method == "DELETE":
item.delete()
data = json.dumps(True)
return HttpResponse(data, mimetype="application/json")
else:
return HttpResponseBadRequest("Invalid request")
那麼這種方法將是根據不同的請求類型做不同的動作。
評論
請注意,這是一個非常,非常簡單的演示。它沒有考慮任何錯誤檢查,用戶認證等。但希望它會給你一些想法。