Understanding RESTful Architecture: http://www.ruanyifeng.com/blog/2011/09/restful
RESTful Design Guide: http://www.ruanyifeng.com/blog/2014/05/restful_api.html
Django REST Framework Documentation: http://www.django-rest-framework.org/#installation
Django RESTful Chinese Translation: http://blog.csdn.net/ppppfly/article/category/6170709
Django-based RESTful installation
First step: Install with PIP:
PIP3 Install DJANGORESTFRAMEWORKPIP3 install djangorestframework-i http://pipy.douban.com/simple #豆瓣源
Step Two: Add rest_framework
to the settings in INSTALLED_APPS
:
Installed_apps = (... ' Rest_framework ',)
If you need to use the browser API and need to add the rest framework's login logoff module, you need to add the following code to urls.py:
Urlpatterns = [ ... URL (r ' ^api-auth/', include (' Rest_framework.urls ', namespace= ' rest_framework '))]
Note: The URL path can be written arbitrarily, but you must include ‘rest_framework.urls‘
and use ‘rest_framework‘
this namespace (namespace). If your Django is a 1.9+ version, you can also not write namespace
, and the REST framework will help you set it up automatically.
Example
Let's look at a simple use case: how to use the rest framework to build a simple API that supports Modle.
We will create a read/write API to process the user information in our project.
The global settings for any rest framework are stored in a configuration dictionary (dictionary, some languages such as map in Java), named REST_FRAMEWORK
. Let's start by adding the following to your settings.py module:
Rest_framework = { # Use Django's standard ' Django.contrib.auth ' Rights Management class, # or give read-only permissions to users who are not authenticated. ' Default_permission_classes ': [ ' rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly ' ]}
Don't forget to make sure you've added rest_framework to your installed_apps.
Now we are ready to create our API. This is the root of our project under the urls.py module:
From django.conf.urls import URL, includefrom django.contrib.auth.models import userfrom rest_framework import routers, S Erializers, viewsets# serializers defines the representation of the API. Class Userserializer (serializers. Hyperlinkedmodelserializer): class Meta: model = User Fields = (' url ', ' username ', ' email ', ' is_staff ') # Viewsets defines the behavior of the view. Class Userviewset (viewsets. Modelviewset): queryset = User.objects.all () Serializer_class = userserializer# routers provides an easy way to automatically configure URLs. Router = routers. Defaultrouter () Router.register (R ' users ', Userviewset) # using automatic URL routing, let's get our API up and running. In addition, we include URLs that log into the visualization API. Urlpatterns = [ url (r ' ^ ', include (Router.urls)), URL (r ' ^api-auth/', include (' Rest_framework.urls ', Namespace= ' Rest_framework ')]
Now you can open your new ' users ' API in the browser's http://127.0.0.1:8000/. Use the login control in the upper right corner to add new and delete actions to system users
From django.conf.urls import URL, include# importing data from an existing assets project models module from assets import modelsfrom rest_framework Import routers,serializers,viewsets# defines a representation of class Userserializer (serializers. Modelseriallizer): class Meta: model = models. UserProfile fields = (' username ', ' name ', ' token ', ' email ', ' is_staff ') class Assetserializer (serializers. Modelserializer): class Meta: model = models. Asset ...
From rest_framework import viewsetsfrom assets import modelsfrom Assets import Rest_searializerclass Userviewset ( Viewsets. Modelviewset): Queryset = models. UserProfile.objects.all () serializer_class = Rest_searializer. Userserializerclass Assetviewset (viewsets. Modelviewset): Queryset = models. Asset.objects.all () serializer_class = Rest_searializer. Assetserializer
rest_urls.py:
From rest_framework import routersfrom django.conf.urls import url,includefrom assets Import Rest_viewsetrouter = routers . Defaultrouter () Router.register (R ' users ', Rest_viewset. Userviewset) Router.register (R ' Assets ', rest_viewset. Assetviewset) Router.register (R ' Manufactory ', Rest_viewset. Manufactoryviewset) Router.register (R ' Business_unit ', Rest_viewset. Businessunitviewset) urlpatterns = [ url (r ', include (Router.urls)), URL (r ' ^api-auth ', include (' Rest_ Framework.urls ', namespace= ' rest_framework ')]
settings.py:
Rest_framework = { # Use Django's standard ' Django.contrib.auth ' Rights Management class, # or give read-only permissions to users who are not authenticated. ' Default_permission_classes ': [ ' rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly ' ]}
Examples of inserting data using the API, views.py:
def api_test (Request): if Request.method = = "GET": return render (Request, "test_post.html") else: data = json.loads (Request. Post.get ("Data")) print ("--->", data) rest_obj = Rest_searializer. Assetserializer (data=data,many=true) if Rest_obj.is_valid (): rest_obj.save () return render (Request, " Test_post.html ", {" Errors ": rest_obj.errors," Data ": Rest_obj.data})
Among them many=true
, is the queryset many-to-many serialization, the detailed parameters will be expressed later.
Dss. Serializer provides sequencer
function serializer (data, datetime_format= ' timestamp ', output_type= ' raw ', Include_attr=none, Except_attr=none, Foreign=false, Many=false)
Parameters:
Data (required| ( QuerySet, Page, list, Django model object)-pending data Datetime_format (optional|string)-converts datetime to the appropriate format if it contains DateTime. The default is " Timestamp "(timestamp) output_type (optional|string)-serialize type. The default "raw" raw data, which returns a list or dictinclude_attr (optional| ( list, tuple)-serializes only the fields in the Include_attr list. The default is Noneexclude_attr (optional| ( list, tuple)-do not serialize fields in the Except_attr list. The default is Noneforeign (Optional|bool)-whether to serialize Foreignkeyfield. Include_attr and exclude_attr are still valid for Foreignkeyfield. The default is Falsemany (Optional|bool)-whether to serialize Manytomanyfield. Include_attr and exclude_attr are still valid for Manytomanyfield default to False
Reference: http://www.django-rest-framework.org/
Reference: http://www.cnblogs.com/ccorz/p/Django-zhiRestful-API.html
Restful API Official Documentation