Compiling RESTful API in Django (1): serialization, djangorestful

Source: Internet
Author: User

Compiling RESTful API in Django (1): serialization, djangorestful

Welcome to my personal website: www.comingnext.cn

About RESTful APIs

Now, in the development process, we often hear the technical term "frontend and backend separation". As the name suggests, the frontend development and backend development are separated. The implementation of this technical solution is to use the API. In short, the API is called by other people who provide the programming interface. After the API is called, it will return data for use. There are a variety of API types, but now more mainstream and practical is to say this article RESTful API, about RESTful API, you can understand through the article of the great god of NLP: http://www.ruanyifeng.com/blog/2011/09/restful

If you are too lazy to read the RESTful API, you can refer to the following RESTful API summary in idea:
1. Each URL represents a resource
2. Some performance Layer for transferring such resources between the client and the server
3. The client uses four HTTP verbs to perform operations on server resources to achieve "transition of performance Layer status ". Specifically:
GET is used to obtain resources, POST is used to create resources (or update resources), PUT is used to update resources, and DELETE is used to DELETE resources.
We should be able to understand this. If you want to have a deep understanding, you need to learn it slowly during development.

I have written this series of blog articles while learning, so there may be some misunderstandings here. Thank you for your attention ~ The main purpose is to exchange, share, and learn

For compiling RESTful APIs for Django, of course the powerful Django library-djangorestframework is used, and the documentation is very detailed. I learned it from the official documentation, this series of articles are based on official documents, so the code and ideas are basically the same. Of course, this is not a simple translation, I have added a lot of my understanding and some situations that may occur in actual operations, including some situations that hope to make your operations faster and easier to understand.

OK. The theme is displayed below.

Build a Development Environment

First of all, it is used in the virtual environment. This is not to mention, the package that needs to be used:

Pip install djangopip install djangorestframeworkpip install pygments # used for code highlighting

Other development environments:

-Pycharm 2017
-Win 10
-Python 3.5

Start

Create a project named tutorial, and then create an snippets APP in this project:

django-admin.py startproject tutorialcd tutorialpython manage.py startapp snippets

After creation, modify INSTALLED_APPS in tutorial/settings. py and add two apps:

1 INSTALLED_APPS = (2... 3 'rest _ framework', 4 'snippets. apps. snippetsconfig', # if Django <1.9, use snippets instead of 5)

 

Create model class

Create an Snippet model class for saving code segments and compile snippets/models. py:

1 from django. db import models 2 from pygments. lexers import get_all_lexers 3 from pygments. styles import get_all_styles 4 5 LEXERS = [item for item in get_all_lexers () if item [1] 6 bytes age_choices = sorted ([(item [1] [0], item [0]) for item in LEXERS]) # obtain all programming languages 7 STYLE_CHOICES = sorted (item, item) for item in get_all_styles ()) # Get all color styles 8 9 10 class Snippet (models. model): 11 created = models. dateTimeField (auto_now_add = True) 12 title = models. charField (max_length = 100, blank = True, default = '') 13 code = models. textField () 14 linanos = models. booleanField (default = False) 15 language = models. charField (choices = LANGUAGE_CHOICES, default = 'python', max_length = 100) 16 style = models. charField (choices = STYLE_CHOICES, default = 'dldly', max_length = 100) 17 18 class Meta: 19 ordering = ('created ',)

 

Except for the comments, other codes are common, which is the same as that in Django development. Then create and migrate data for this model (Here we only want to demonstrate it, so the database we use is the sqlite that comes with Django ):

python manage.py makemigrations snippetspython manage.py migrate

 

Create a serialization class

Now, we start to serialize the title of the article. First, explain serialization: here we can simply understand it as serializer (A Django-REST-Framework serialization library will be introduced by the code below) convert the model instance to json format and then respond to it, so that it can be used for parsing during client calls.

For example, a PostModel contains two fields: title and author, which are serialized in json format such as {'title': 'restful API 'and 'author': 'ziv, in this way, it is more suitable for resolution of various clients.

The deserialization principle is similar, and the data format after deserialization is easier to use in the background. Some examples will be provided to help you better understand it.

After the serialization is explained, you need to repeat the code and create a serializers. py under snippets. The Code is as follows:

1 from rest_framework import serializers 2 from snippets. models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES 3 4 5 class SnippetSerializer (serializers. serializer): 6 id = serializers. integerField (read_only = True) 7 title = serializers. charField (required = False, allow_blank = True, max_length = 100) 8 # use the field flag to control the display template 9 code = serializers when the serializer renders the HTML page. charField (style = {'base _ template': 'textarea.html '}) 10 linnos = serializers. booleanField (required = False) 11 language = serializers. choiceField (choices = LANGUAGE_CHOICES, default = 'python') 12 style = serializers. choiceField (choices = STYLE_CHOICES, default = 'dldly') 13 14 # given the verified data, create and return a new Snippet instance 15 def create (self, validated_data ): 16 return Snippet. objects. create (** validated_data) 17 18 # given the verified data, update and return an existing Snippet instance 19 def update (self, instance, validated_data): 20 instance. title = validated_data.get ('title', instance. title) 21 instance. code = validated_data.get ('code', instance. code) 22 instance. linnos = validated_data.get ('linano', instance. linux) 23 instance. language = validated_data.get ('language ', instance. language) 24 instance. style = validated_data.get ('style', instance. style) 25 instance. save () 26 return instance

The create and update Methods define how to create or modify a complete instance when serializer. save () is called.

 

The following line of code:

code = serializers.CharField(style={'base_template':'textarea.html'})

What you need to know for the moment is that its function is to control the display template when the serializer renders the HTML page. As for why, it is particularly useful for controlling how to display the browsed API, this will be seen in later articles.
Use the serializer

First, enter the shell mode:

python manage.py shell

 

The next step is to create and save the Snippet model instance as you did when learning Django's orm:
>>> from snippets.models import Snippet>>> from snippets.serializers import SnippetSerializer>>> from rest_framework.renderers import JSONRenderer>>> from rest_framework.parsers import JSONParser>>> snippet = Snippet(code='foo = "bar"\n')>>> snippet.save()>>> snippet = Snippet(code='print "hello, world"\n')>>> snippet.save()

 

When you view the database, you will find that there are two more rows of data in the relevant table, that is, the data we just created:

You can also view it in shell:

>>> serializer = SnippetSerializer(snippet)>>> serializer.data{'code': 'print "hello, world"\n', 'title': '', 'linenos': False, 'style': 'friendly', 'language': 'python', 'id': 2}

 

Render data in json format:

>>> content = JSONRenderer().render(serializer.data)>>> contentb'{"id":2,"title":"","code":"print \\"hello, world\\"\\n","linenos":false,"language":"python","style":"friendly"}'

 

The json format has already appeared. That is to say, the data in json format is to be displayed on a URL. You can probably feel that when we access a URL, the above heap of data will be returned for your use. This completes a serialization process and shows the prototype of the client.

Serialization is to return data in json format to the client for viewing and using data. When the client needs to modify, add, or delete data, the process should be reversed, that is, deserialization, deserializes the json format data submitted by the client.

The following code parses the json data stream into the data format that comes with Python to facilitate Django operations in the background:

>>> from django.utils.six import BytesIO>>> stream = BytesIO(content)>>> data = JSONParser().parse(stream)

 

Check and save the data:

>>> serializer = SnippetSerializer(data=data)>>> serializer.is_valid()True>>> serializer.validated_dataOrderedDict([('title', ''), ('code', 'print "hello, world"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])>>> serializer.save()<Snippet: Snippet object>

 

In this case, another piece of data is added to the database:

 

Use ModelSerializers

In the above SnippetSerializer class, we inherit serializers. serializer class. We can see that many codes in the SnippetSerializer class are actually used with models. the Snippet model in py is similar, so we can improve it here. Just as the Form class and ModelForm class are provided in Django, django-rest-framework provides the Serializer class and ModelSerializer class for us. We can use it to make our code much simpler. Modify serializers. py:

1 class SnippetSerializer(serializers.ModelSerializer):2     class Meta:3         model = Snippet4         fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

 

We can check all fields in the serializer instance by printing in shell:

>>> from snippets.serializers import SnippetSerializer>>> serializer = SnippetSerializer()>>> print(repr(serializer))

 

The following figure shows the effect after printing ):

(The two graphs are printed at the same time, which is too long to be separated)

In our new SnippetSerializer class, we can find that the comparison code is much less than the previous one, which reflects the efficiency of the ModelSerializer class:

-Automatically determine Fields

-Simple default implementation of the create and update Methods

Compile a common Django View

The next step is to use our new Serializer class to write some API views. Edit snippets/views. py:

1 from django. http import HttpResponse, JsonResponse 2 from django. views. decorators. csrf import csrf_exempt 3 from rest_framework.renderers import JSONRenderer 4 from rest_framework.parsers import JSONParser 5 from snippets. models import Snippet 6 from snippets. serializers import SnippetSerializer 7 8 9 # Create your views here.10 @ csrf_exempt11 def snippet_list (request ): 12 "13. list all existing snippet or create a new snippet14" 15 if request. method = 'get': 16 snippets = Snippet. objects. all () 17 serializer = SnippetSerializer (snippets, bytes = True) 18 return JsonResponse (serializer. data, safe = False) 19 20 elif request. method = 'post': 21 data = JSONParser (). parse (request) 22 serializer = SnippetSerializer (data = data) 23 if serializer. is_valid (): 24 serializer. save () 25 return JsonResponse (serializer. data, status = 201) 26 return JsonResponse (serializer. errors, status = 400) 27 28 29 @ csrf_exempt30 def snippet_detail (request, pk): 31 "32 search to view, update, or delete a code segment 33" 34 try: 35 snippet = Snippet. objects. get (pk = pk) 36 TB Snippet. doesNotExist: 37 return HttpResponse (status = 404) 38 39 if request. method = 'get': 40 serializer = SnippetSerializer (snippet) 41 return JsonResponse (serializer. data) 42 43 elif request. method = 'put': 44 data = JSONParser (). parse (request) 45 serializer = SnippetSerializer (snippet, data = data) 46 if serializer. is_valid (): 47 serializer. save () 48 return JsonResponse (serializer. data) 49 return JsonResponse (serializer. errors, status = 400) 50 51 elif request. method = 'delete': 52 snippet. delete () 53 return HttpResponse (status = 204)

 

The above code is easy to understand and defines different operations in the background for different http actions, which also reflects the concept of restful API.

Remember to add the @ csrf_exempt modifier.

To call the view function, you must design the url. The process here is the same as that in Django development. First create snippets/urls. py:

1 from django.conf.urls import url2 from snippets import views3 4 urlpatterns = [5     url(r'^snippets/$', views.snippet_list),6     url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),7 ]

 

Next, tutorial/urls. py. The Code is as follows:

from django.conf.urls import url, includeurlpatterns = [    url(r'^', include('snippets.urls')),]

 

Test the API

After completing the above work, you can start the test. Exit the shell mode and start the server. To send a request according to the url we just designed, you must first install the httpie module:

pip install httpie

 

Then access the service in the command line window. The effect is as follows:
You can also access the data of the specified id:
Of course, you can also directly view it in the browser and enter the URL:

At this point, a function is implemented. When someone else accesses this URL, data in json format is returned for the user.

In the next article, we will explain how to process requests and responses. Thank you for your support ~

Related Article

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.