原文地址:http://blog.csdn.net/thinkinside/article/details/7236807
源代碼下載地址:留言寫下郵箱地址,一天內會發送給你全部源代碼
#####################Django實現RESTFul web service#####################################################################################################
Ajax 統治了Web開發中的客戶端,REST成為了WEB世界中最流行的架構風格。選擇變的簡單了:前端Ajax訪問后端的RESTFul web service對資源進行操作。
Django中有可選的REST framework,選用了DJANGO REST framework。框架特點:
- 該框架對resource,serializer,renderer/parser,view和response的定義清晰,有很符合django的MTV模式
- 對於認證和授權有很好的支持
- 內置了一些Mixin,可以隨意組裝
Django REST framework 實現購物車(Cart)的RESTFul web service:
- 安裝:從http://pypi.python.org/pypi/djangorestframework/0.3.2 下載v0.3.2,解壓后$sudo python setup.py install
- 配置:settings文件中加入'djangoframework'這個app
- 使用:最常見的用法是
- 定義資源:資源將python對象(比如model)進行隔離,組裝,生成需要序列化(serialize)的數據,除了基本的Resource之外,還提供了FormResource和ModelResource,以便於對form和model進行處理,Resource有助於view中的處理
- 創建視圖:視圖是對django View的封裝,並定義了序列化,反序列化等方法,同時通過Mixin 實現get,post,delete,put等操作,框架內置了ModelView和ModelResource配合使用非常方便簡單
- 定義url:將正則表達式匹配View類的as_view方法,該方法會返回django的view函數
本個例子中處理的不是購物車本身,而是購物車中的line_item,屬於model類,使用ModelResource和ModelView是最方便的,實現如下:
- 創建depotapp/resource.py:
from django.core.urlresolvers import reverse from djangorestframework.views import View from djangorestframework.resource import ModelResource from models import * class LineItemResource(ModelResource): model = LineItem fields = ('product', 'unit_price', 'quantity') def product(self, instance): #重新定義關聯的對象。LineItem關聯到了Product,在resource中將product屬性重新定義為product.title return instance.product.title
- 使用ModelView定義url:/depot/depotapp/urls.py
from djangorestframework.views import ListOrCreateModelView, InstanceModelView from resources import * #加入 (r'API/cart/items', ListOrCreateModelView.as_view(resource=LineItemResource))
- 訪問http://localhost:8000/depotapp/API/cart/items/看到了產生的RESTFul API了:
圖中所示:可以渲染成json,html,xhtml,txt,xml等格式。
一般情況來說,這樣就可以了。但是由於我們這里的LineItem不是從數據庫中獲得的,而是從session中的cart對象獲取到的,所以要做改造:
- 框架提供了ListOrCreateModelView繼承了ModelView,同時混合了ListModelMixin和CreateModelMixin。而ListOrCreateModel定義了get方法,方法使用models.objects.all()從數據庫中獲取數據,所以我們應該修改一下View的行為,讓其從session中獲取數據,再定義一個View類在depotapp/views.py中
from djangorestframework.views import View class RESTforCart(View): def get(self, request, *args, **kwargs): return request.session['cart'].items
- 修改url為:(r'API/cart/items', RESTforCart.as_view(resource=LineItemResource))
- 再訪問 http://localhost:8000/depotapp/API/cart/items/,就可以顯示購物車中的item了。默認的是html 渲染,可以通過http://localhost:8000/depotapp/API/cart/items/?format=json 訪問json渲染
- 用Django REST framework實現RESTFul web service ,靈活簡單。
#####################Django+jquery+ajax###############################################################################################################
已經有了一個使用json格式的RESTFul API了,可以實現這樣的功能了:為了避免產品列表和購物車之間來回切換,需要在產品列表界面上添加顯示購物車,並且通過ajax方式不斷刷新界面就更新購物車的顯示內容。
ajax的框架選擇jquery。
Django 使用 jquery:
在depotapp/static下面創建js文件夾,放入jquery庫,如jquery.js。然后在模板界面當中引入就行了。假定所有的界面都使用jquery,希望能夠編寫出Unobtrusive JavaScript 所以在base.html中在</body>之前加入以下幾行內容:
<script src="/static/js/jquery.js"></script> {% block js %} <!-- 插入具體界面引用的js庫,或者js代碼--> {% endblock %} <script> $(function(){ <!--這里編寫base界面的on_ready代碼--> {% block on_ready %} <!--這里插入具體的代碼--> {% endblock %} }); </script>
嵌入購物車界面如下,需要做兩件事情:
- 修改模板
depotapp/templates/depotapp/store.html {% extends "base.html" %} {% block title %} 產品目錄 {% endblock %} {% block pagename %} 產品目錄 {% endblock %} {% block content %} <div class="row"> <div class="span10"> {% for item in products %} <div class="row" style="padding-top:10"> <div class="span3 media-grid"> <a href="#"> <img class="thumbnail" src="{{item.image_url}}" alt=""> </a> </div> <div class="span6"> <h3>{{item.title}}</h3> <br/> {{item.description}} <br/> <br/> <br/> <div class="row"> <div class="span2"><h3>¥{{item.price|floatformat:"2"}}</h3></div> <div class="span"><a class="btn primary" href="{% url depotapp.views.add_to_cart item.id %}">加入購物車</a></div> </div> </div> </div> <div class="page-header"> </div> {% endfor %} </div><!--span10--> <div class="span4"> <h5>我的購物車</h5><br/> <table class="condensed-table"> <tbody> {% for item in cart.items %} <tr> <th>{{item.quantity}}x</th> <td>{{item.product.title}}</td> <td>¥{% widthratio item.quantity 1 item.unit_price %} </td> </tr> {% endfor %} <tr> <td></td> <th>總計:</th> <th>¥{{cart.total_price|floatformat:"2"}}</th> </tr> </tbody> </table> <a class="btn danger" href="{% url depotapp.views.clean_cart %}">清空</a> <a class="btn success" href="#">結算</a> </div><!--span4--> {% endblock %}
- 在depotapp/views中的store_view視圖函數中增加一行:cart = request.session.get("cart", None),就可以顯示界面了。
編寫javascript實現ajax:最后一步就是通過javascript實現,點擊加入購物車的時候,調用server端的RESTful API,同時更改界面購物車上的內容。
通過ajax請求后台服務,首先要實現后台服務,關於加入購物車需要一下定義:
url: http://localhost:8000/depotapp/API/cart/items/post
post數據: product = product_id
處理過程: 根據product_id,將product加入購物車
返回:購物車中的所有條目
service(depotapp/views.py中的RESTforCart類)增加一個方法:
def post(self, request, *args, **kwargs): print request.POST['product'] product = Product.objects.get(id=request.POST['product']) cart = request.session['cart'] cart.add_product(product) request.session['cart'] = cart return request.session['cart'].items
可以通過http://localhost:8000/depotapp/API/cart/items/post來測試服務接口(使用Firebug調試是非常方便的辦法):
如同你看到的那樣,我們的接口定義不是完全RESTful,在生成的表單中,我們只需要選擇Product,不用管另外的兩個表單項,POST之后就可以從之前實現的購物車界面中看到新增加的產品項了。
服務測試接口通過,就可以在界面中通過ajax調用了,jquery對ajax提供了豐富的支持,為了方便使用jquery的selector,先要對html進行改造,將depot/templates/depotapp/store.html中,迭代產品的部分改成如下的樣子:
{% for item in products %} <div class="row" style="padding-top:10"> <div class="span3 media-grid"> <a href="#"> <img class="thumbnail" src="{{item.image_url}}" alt=""> </a> </div> <div class="span6"> <h3>{{item.title}}</h3> <br/> {{item.description}} <br/> <br/> <br/> <div class="row"> <div class="span2"><h3>¥{{item.price|floatformat:"2"}}</h3></div> <div class="span"><a class="btn primary" productid="{{item.id}}" href="#">加入購物車</a></div> </div> </div> </div> <div class="page-header"> </div> {% endfor %}
主要修改了“加入購物車”的<a>標簽,增加了productid屬性,將href改為“#”,這樣就可以方便的添加事件:
//store.html on ready $('a.btn[productid]').bind("click",function(){ alert($(this).attr("productid")); } );
實現的功能是:對於所有的<a>標簽,如果class包含“btn”,並且擁有“productid”屬性的元素,添加click事件,彈出的對話框顯示“productid”的屬性值。
打開產品清單界面測試一下,能夠正確的彈出產品ID,然后就可以編寫ajax的處理的。這里使用jquery.post()方法,jquery.post()是jquery.ajax的簡化寫法,如下:
//store.html on ready $('a.btn[productid]').bind("click",function(){ var product_id=$(this).attr("productid"); //alert(product_id); $.post("/depotapp/API/cart/items/post", {product:product_id}, function(data){ alert(data); } ); } );
彈出的對話框的data就是前邊API接口的返回值,即現有購物車中的條目列表。???
最后,根據返回的數據更改界面上的購物車顯示,這里為了方便也對html改造,整個store.html如下
{% extends "base.html" %} {% block title %} 產品目錄 {% endblock %} {% block pagename %} 產品目錄 {% endblock %} {% block content %} <div class="row"> <div class="span10"> {% for item in products %} <div class="row" style="padding-top:10"> <div class="span3 media-grid"> <a href="#"> <img class="thumbnail" src="{{item.image_url}}" alt=""> </a> </div> <div class="span6"> <h3>{{item.title}}</h3> <br/> {{item.description}} <br/> <br/> <br/> <div class="row"> <div class="span2"><h3>¥{{item.price|floatformat:"2"}}</h3></div> <div class="span"><a class="btn primary" productid="{{item.id}}" href="#">加入購物車</a></div> </div> </div> </div> <div class="page-header"> </div> {% endfor %} </div><!--span10--> <div class="span4"> <h5>我的購物車</h5><br/> <table id="tabCart" class="condensed-table"> <tbody id="items"> </tbody> <tfoot> <tr> <td></td> <th>總計:</th> <td id="totalprice">¥{{cart.total_price|floatformat:"2"}}</td> </tr> </tfoot> </table> <a class="btn danger" href="{% url depotapp.views.clean_cart %}">清空</a> <a class="btn success" href="#">結算</a> </div><!--span4--> {% endblock %} {% block js %} <!--js from store.html--> <script> function refreshCart(items){ total = 0; var tbody = $('tbody#items')[0]; tbody.innerHTML = ""; for(var i=0;i<items.length;i++){ total+=items[i].quantity*items[i].unit_price; $('table#tabCart').append('<tr><td>'+items[i].quantity+'x</td>'+ '<td>'+items[i].product+'</td><td>¥'+items[i].unit_price+ '</td></tr>'); } $('#totalprice')[0].innerHTML = '$'+total; } </script> {% endblock %} {% block on_ready %} //store.html on ready $.getJSON('/depotapp/API/cart/items/',refreshCart); $('a.btn[productid]').bind("click",function(){ var product_id=$(this).attr("productid"); //alert(product_id); $.post("/depotapp/API/cart/items/post",{product:product_id},refreshCart); } ); {% endblock %}
定義了一個refreshCart函數,根據參數”重繪“購物車界面。在$(document).ready部分,首先調用前面實現的API顯示購物車,這樣我們在模板中就可以去掉原來實現的”購物車“,改成javascript的方式。
然后為每個”加入購物車“按鈕添加點擊事件,調用本節開始部分實現的接口,根據返回的最新條目數據調用refreshCart函數重繪購物車。
上面的模板中,javascript的部分划分成了兩個block:{% block js %}用於嵌入具體頁面(相對應父模板)的js函數;{% block on_ready %}用於嵌入具體頁面的$(document).ready處理。結合base.html中定義的block,可以使組合在一起的具體頁面和模板頁面符合Unobtrusive JavaScript 。這樣做應該是Django+jquery實現ajax的最佳實踐。