Using Django to implement RESTful APIs (i)

Source: Internet
Author: User
Tags install django pip install django

The RESTful API is now popular, and here is its introduction to understanding restful architectures and RESTful API design guidelines. As a general rule of Django, you can certainly implement REST, but there is a quicker, more powerful way to do that is Django REST framework.它是python的一个模块,通过在Django里面配置就可以把app的models中的各个表实现RESTful API。下面是实现方法:

First, installation configuration
pip install djangorestframeworkpip install markdown        # Markdown support for the browsable API. Pip Install Django-filter  #  Filtering Support

and add it to the Django settings.py . INSTALLED_APPSrest_framework,如下:

Installed_apps = (...    ')    Rest_framework ',)

Add URLs for the rest_framework login and logout views of the framework in the url.py file of the root directory:

Urlpatterns = [    ...    URL (r ' ^api-auth/', include (' Rest_framework.urls ', namespace= ' rest_framework '))]

Ii. Creating model and serializer

Create an app with the name snippets : Add a table to the view models.py as follows:

 fromDjango.dbImportModels fromPygments.lexersImportGet_all_lexers # A module that implements code highlighting fromPygments.stylesImportget_all_styleslexers= [item forIteminchGet_all_lexers ()ifItem[1]]language_choices= Sorted ([(Item[1][0], item[0]) forIteminchLexers]) # Get options for all programming languages Style_choices= Sorted (item, item) forIteminchget_all_styles ()) # list all color stylesclassSnippet (models. Model): Created= Models. Datetimefield (auto_now_add=True) Title= Models. Charfield (max_length=100, Blank=true, default="') Code=models. TextField () Linenos= Models. Booleanfield (default=False) Language= Models. Charfield (Choices=language_choices, default='python', max_length=100) style= Models. Charfield (Choices=style_choices, default='Friendly', max_length=100)    classmeta:ordering= ('created',)

Then start syncing to the database:

./manage.py makemigrations snippets./manage.py Migrate

The next thing to do is create the serializer class, similar to the Form. It does this by extracting the data you need from the parameters you pass in and converting it into a JSON format (note that it is already a bytecode) while supporting deserialization to the model object. Insnippets 文件夹中添加 serializers.py 并在其添加如下:

 fromRest_frameworkImportserializers fromSnippets.modelsImportSnippet, language_choices, Style_choicesclassSnippetserializer (serializers. Serializer): # It is serialized in a way similar to the Django forms ID= serializers. Integerfield (read_only=True) Title= serializers. Charfield (Required=false, Allow_blank=true, max_length=100) Code= serializers. Charfield (style={'base_template':'textarea.html'}) # style is set equal to Django's widget=widgets.Textarea Linenos= serializers. Booleanfield (required=False) # is used to display language on the browser= serializers. Choicefield (Choices=language_choices, default='python') style= serializers. Choicefield (Choices=style_choices, default='Friendly')    defCreate (self, validated_data):"""Create and return a new ' Snippet ' instance, given the validated data. """        returnSnippet.objects.create (* *validated_data)defUpdate (self, instance, Validated_data):"""Update and return an existing ' Snippet ' instance, given the validated data. """Instance.title= Validated_data.get ('title', Instance.title) Instance.code= Validated_data.get ('Code', Instance.code) Instance.linenos= Validated_data.get ('Linenos', Instance.linenos) instance.language= Validated_data.get ('language', instance.language) Instance.style= Validated_data.get ('style', Instance.style) instance.save ()returnInstance

Third, the use of serializer

Use the./manage.py Shell to enter the Django Shell first. The operation is as follows:

You can see the use of serializer as a Django forms. It is deserialized as follows:

 from Import  == Jsonparser (). Parse (Stream)

This is to convert the resulting data into an example:

Serializer = Snippetserializer (data=data) serializer.is_valid ()    # Start Validation #  True  Serializer.validated_data#  ordereddict ([' title ', ' '), (' Code ', ' print ' Hello, world ' \ n '), (' Linenos ', False), (' Language ', ' Python '), (' style ', ' friendly ')])serializer.save ()#  < Snippet:snippet object>

At the same time, we can also serialize the querysets, simply by setting the parametersmany=True,如下:

Serializer = Snippetserializer (Snippet.objects.all (), many=True) serializer.data#  [ Ordereddict (' id ', 1), (' title ', U '), (' Code ', u ' foo = "bar" \ n '), (' Linenos ', False), (' Language ', ' Python '), (' style ', ' Friendly ')], ordereddict ([' ID ', 2), (' title ', U '), (' Code ', u ' print "Hello, world" \ n '), (' Linenos ', False), (' Languag E ', ' Python '), (' style ', ' friendly ')]), ordereddict ([' ID ', ' 3 '), (' title ', U '), (' Code ', u ' print "Hello, World"), (' Linen Os ', False), (' Language ', ' Python '), (' style ', ' friendly ')])

Iv. Use of ModelSerializer

ModelSerializerSimilar to Django's modelform, you can directly associate to a table in models. As follows:

classSnippetserializer (serializers. Modelserializer):classMeta:model=Snippet Fields= ('ID','title','Code','Linenos','language','style')

V. Using in the Django view Serializer

First, you can write the same way as the regular Django view, returning the serialized output data.

 fromDjango.httpImportHttpResponse, Jsonresponse fromDjango.views.decorators.csrfImportcsrf_exempt fromRest_framework.renderersImportJsonrenderer fromRest_framework.parsersImportJsonparser fromSnippets.modelsImportSnippet fromSnippets.serializersImportsnippetserializer@csrf_exemptdefsnippet_list (Request):"""List All code snippets, or create a new snippet. """    ifRequest.method = ='GET': Snippets=Snippet.objects.all () serializer= Snippetserializer (Snippets, many=True)returnJsonresponse (Serializer.data, safe=False)elifRequest.method = ='POST': Data=Jsonparser (). Parse (request) Serializer= Snippetserializer (data=data)ifserializer.is_valid (): Serializer.save ()returnJsonresponse (Serializer.data, status=201)        returnJsonresponse (Serializer.errors, status=400)

You can also write a view corresponding to its models table, the implementation of its deletion, change, check.

@csrf_exemptdefSnippet_detail (Request, PK):"""Retrieve, update or delete a code snippet. """    Try: Snippet= Snippet.objects.get (pk=PK)exceptsnippet.doesnotexist:returnHttpResponse (status=404)    ifRequest.method = ='GET': Serializer=Snippetserializer (snippet)returnjsonresponse (serializer.data)elifRequest.method = ='PUT': Data=Jsonparser (). Parse (request) Serializer= Snippetserializer (Snippet, data=data)ifserializer.is_valid (): Serializer.save ()returnjsonresponse (serializer.data)returnJsonresponse (Serializer.errors, status=400)    elifRequest.method = ='DELETE': Snippet.delete ()returnHttpResponse (status=204)

Add the corresponding URL,snippets/urls.py 中设置如下:

 from Import URL  from Import  = [    url (r'^snippets/$', views.snippet_list),    URL (r  '^snippets/(? p<pk>[0-9]+)/$', Views.snippet_detail),]

Finally, add the corresponding mappings in the url.py of the root directory.

Urlpatterns = [
... URL (r'^', include ('snippets.urls')),]

At this point, all the configuration has been completed. The next step is to test our API

VI. TEST API

For convenience we can use the Httpie module to test, start Django, and then enter in the client http://127.0.0.1:8000/snippets/,操作如下:

So simple .....

Using Django to implement RESTful APIs (i)

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.