Django RESTful study one of the first test examples

Source: Internet
Author: User

I. Building new projects and apps

django-admin.py startproject tutorialcd Tutorialpython manage.py Startapp Snippets

Two. Configure the database

DATABASES ={' default ': {' ENGINE ': ' Django.db.backends.sqlite3 ', ' NAME ': ' tmp.db ', ' USER ': ', ' PASSWORD ': ', ' HOST ': ', ' PORT ': ',}}

Three. Configure the settings.py to add the new app

Installed_apps = (... ' rest_framework ', ' snippets ',)

Four. Configure URLs

Urlpatterns = Patterns ("", url (r ' ^ ', include (' Snippets.urls ')),)

Five. Create model

from django.db import modelsfrom pygments.lexers import get_all_lexersfrom  Pygments.styles import get_all_styleslexers =[item for item in get_all_ Lexers () if item[1]]language_choices = sorted ([(item[1][0], item[0])  for item  in lexers]) style_choices = sorted ((Item, item)  for item in get_ All_styles ()) Class snippet (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 ',)

Note that rest3.0 is different from version 2.0, such as a widget that is represented by a style. field is to be represented by Readonlyfield.

Then synchronize the database

Python manage.py syncdb

Seven. Creating a class of serialized serializer

We need to provide a serialization and inverse serialization method for the Web API, using data formats such as JSON to represent the snippet data model. We can declare a serializer class like the Django form class. Create a file named serializers.py in the app snippets directory and type it in the file:

from django.forms import widgetsfrom rest_framework import serializersfrom  Snippets.models importsnippet, language_choices, style_choicesclass snippetserializer ( serializers. Serializer):     pk = serializers. Field () # note:  ' field '  is an untyped read-only field.     title = serializers. Charfield (required=false,                                    max_length=100)     code = serializers. Charfield (widget=widgets. textarea,                                  max_ length=100000)    &NBsp;linenos = serializers. Booleanfield (Required=false)     language = serializers. Choicefield (choices=language_choices,                                         default= ' python ')     style =  serializers. Choicefield (choices=style_choices,                                      default= ' friendly ') def restore_object (self, attrs, instance =none): "" "        Create or update a new  Snippet instance, given a dictionary       &nbSp;of deserialized field values. Creating or updating a new  snippet  instance requires a dictionary that contains the values of the inverse serialized field.         note that if we don ' t define  This method, then deserializing        data will      simply return a dictionary of items. If we do not define the modification method, the nanosecond inverse serialization data will simply return a project dictionary          "" "if instance:#  update existing instance             Instance.title = attrs.get (' title ',  instance.title)              instance.code = attrs.get (' Code ',  instance.code)              instance.linenos = attrs.get (' Linenos ',  instance.linenos)        &nbsP;    instance.language = attrs.get (' language ',  instance.language)              instance.style = attrs.get (' style ') ,  instance.style)     return instance         # create new instancereturnsnippet (**attrs)          return snippet (**attrs)

Understanding of Serialization classes:

The first part of the serializer class defines the domains that need to be serialized and deserialized. The Restore_object method defines how to create a new instance of the inverse serialized data.

Note: We can also use more of the other properties used in the form, like Widgets (3.0 with style) =weidgets. Textarea. These properties can be used to control the behavior of the serializer rendering an HTML form, especially useful for displaying browsable APIs, which we'll see in a later tutorial.

We can use the Modelserializer class to generate it quickly, but now we're going to show you how to define the serializer.

Eight. See how serialization Works

Python manage.py Shell
From snippets.models import snippetfrom snippets.serializers import Snippetserializerfrom rest_framework.renderers Import jsonrendererfrom rest_framework.parsers import jsonparsersnippet =snippet (code= ' foo = "bar" \ n ') Snippet.save () Snippet =snippet (code= ' print "Hello, world" \ n ') Snippet.save ()

Create a snippets instance above

Get the snippets instance to see the effect of serialization:

Serializer =snippetserializer (snippet) serializer.data# {' PK ': 2, ' title ': U ', ' Code ': U ' print ' Hello, world ' \ n ', ' Linenos ': False, ' language ': U ' python ', ' style ': U ' Friendly '}

Above we convert an instance of the model into a Python data type. We use the serializer to render it as JSON:

Content =jsonrenderer (). Render (Serializer.data) content# ' {"PK": 2, "title": "", "Code": "Print \ \" Hello, world\\ "\\n", " Linenos ": false," language ":" Python "," style ":" Friendly "} '

Nine. Inverse serialization

The inverse serialization is similar, first we parse the data stream and turn it into a Python data type.

==jsonparser (). Parse (Stream)

Then store the Python data type into the object instance.

Serializer =snippetserializer (Data=data) serializer.is_valid () # trueserializer.object# <snippet:snippet Object >

Note the similarities between these APIs and the Django forms. These similarities are more pronounced when we talk about using serializers in view.

I can also serialize querysets, simply add many = True.

Serializer =snippetserializer (Snippet.objects.all (), many=true) serializer.data# [{' PK ': 1, ' title ': U ', ' Code ': U ' foo = "Bar" \ n ', ' Linenos ': False, ' language ': U ' python ', ' style ': U ' Friendly '}, {' PK ': 2, ' title ': U ', ' Code ': U ' print ' Hello , world "\ n ', ' Linenos ': False, ' language ': U ' python ', ' style ': U ' friendly '}]


This article is from the "Automation Rolin" blog, so be sure to keep this source http://luoguoling.blog.51cto.com/1568501/1688139

Django RESTful study one of the first test examples

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.