Django practice (15): Django implements restful Web Service

Source: Internet
Author: User

Once upon a time, Ajax had dominated the web development client, while rest became the most popular architecture style in the web world ). Therefore, our choice becomes simple: The frontend Ajax accesses the backend restful web service to operate resources.
Django has some optional rest frameworks, such as Django-piston and Django-tasypie. But Google and I recommend this: Django rest framework. This framework has the following features:
1. Good name! Direct topic
2. Because of the good name, Google search (Django rest/Django restful) ranks first
3. Of course, the first two reasons are all joke. The most important reason is that the framework has clear definitions of resource, serializer, Renderer/parser, view, and response, and is in line with Django's MTV mode (for example, its view is implemented by wrapping Django's view ). Using this framework in Django is almost natural.
4. good support for authentication and authorization.
5. A series of built-in mixins can be assembled at will.

 

The following uses Django rest framework to implement the restful Web Service of cart.
Step 1: Install
The official documentation says Pip or easy_install can be used for installation. However, some features are lost if easy_install is not the latest version. Therefore, we recommend that you useSource codeInstallation Method:
Download v0.3.2 from the http://pypi.python.org/pypi/djangorestframework/0.3.2, unzip it, and install $ sudo Python setup. py

Step 2: Configure
Add the following to installed_apps of depot/settings. py:
'Djangorestframework ',

Step 3: Use
Django rest framework has many "usage". The most common usage is:
1. Define resources. Resources isolate and assemble Python objects (such as model objects) to generate data that needs to be serialized (serialize. In addition to the basic resource types, the framework also provides formresource and modelresource for Processing Form or model. Resource is helpful for processing in the view. Of course, you can specify the data to be serialized in the view without using resource.
2. Create a view. A view encapsulates Django view and defines methods such as serialization and deserialization. Meanwhile, it supports get, post, put, delete, and other operations through Mixin. The Framework has built-in modelview, which is easy to use with modelresource.
3. Define the URL and use the as_view method of the View class that matches the regular expression. This method returns the view function of Django.

In our example, it is not the shopping cart, but the line_item in the shopping cart, which belongs to the model class. Therefore, using modelresource and modelview is the most convenient. Specific implementation:
Create depotapp/resources. py

 From Django. Core. urlresolvers Import Reverse
From Djangorestframework. Views Import View
From Djangorestframework. Resources Import Modelresource
From Models Import *

Class Lineitemresource (modelresource ):
Model = lineitem
Fields = ( ' Product ' , ' Unit_price ' ,' Quantity ' )
Def Product (self, instance ):
Return Instance. Product. Title

The associated objects are redefined. For example, lineitem is associated with the product, but the product attribute is redefined as product. title in the resource.

Then use modelview to define the URL: Add URL ing in the urlpatterns of depot/depotapp/URLs. py. Of course, you should first introduce the relevant modules:

Depot/depotapp/URLs. py

 From Django. conf. URLs. defaults Import *
From Models Import *
From Views Import *
From Djangorestframework. Views Import Listorcreatemodelview, instancemodelview
From Resources Import *
Urlpatterns = patterns ( '' ,
(R ' Product/create/$ ' , Create_product ),
(R' Product/LIST/$ ' , List_product ),
(R ' Product/edit /(? P <ID> [^/] +)/$ ' , Edit_product ),
(R ' Product/View /(? P <ID> [^/] +)/$ ' , View_product ),
(R ' Store/$ ' , Store_view ),
(R' Cart/View/ ' , View_cart ),
(R ' Cart/clean/ ' , Clean_cart ),
(R ' Cart/Add /(? P <ID> [^/] +)/$ ' , Add_to_cart ),
(R ' API/cart/items ' , Listorcreatemodelview. as_view (resource = lineitemresource )),
)

Now you can access http: // localhost: 8000/depotapp/API/cart/items/to view the generated restful API:

, You can render (render) into JSON, HTML, XHTML, txt, XML and other formats. Of course, you can also add your own rendering, such as yaml

In general, this is enough. However, because lineitem is not obtained from the database but from the cart object in the session, some modifications are required.
The listorcreatemodelview provided by the Framework inherits the modelview and integrates the listmodelmixin and createmodelmixin. While listmodelmixin defines the get method, which uses model. objects. all () is to get data from the database, so we should modify the view behavior to get data from the session. You may wish to get the data in depotapp/views. custom View class in Py:

FromDjangorestframework. ViewsImportView
ClassRestforcart (View ):
DefGet (self, request, * ARGs, ** kwargs ):
ReturnRequest. session ['Cart']. Items

Then change the URL to: (r 'api/cart/items ', restforcart. as_view (resource = lineitemresource), and then access http: // localhost: 8000/depotapp/API/cart/items/to display items in the shopping cart. The default is HTML Rendering. You can use http: // localhost: 8000/depotapp/API/cart/items /? Format = JSON access JSON rendering:

 
[{"Product": "\ u7a81 \ u7136 \ u5c31 \ u8d70 \ u5230 \ u4e86 \ u897f \ u85cf", "unit_price": "12", "quantity": 2 }, {"product": "\ u9ec4 \ u74dc \ u7684 \ u9ec4 \ u897f \ u74dc \ u7684 \ u897f", "unit_price": "12", "quantity": 38}]

using Django rest framework to implement restful Web Services is simple and flexible.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.