Django-rest-framework quick start,

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

Django-rest-framework quick start,

The first contact with django-rest-framework was during the internship. I didn't understand it at the time, and it was awesome to see that the view was written using the class method. Because the official website is in English, there is still a little resistance to my learning, so I didn't learn much at that time. It's really cheap. In fact, I have patience on the official website. I certainly can understand my 6-level 410 skills. The reason was that I was too impetuous.

 

Introduction to Django rest framework

Django REST framework is a powerful and flexible toolkit for building Web APIs.

Some reasons you might want to use REST framework:

  • The Web browsable API is a huge usability win for your developers.
  • Authentication ies including packages for OAuth1a and OAuth2.
  • Serialization that supports both ORM and non-ORM data sources.
  • Customizable all the way down-just use regular function-based views if you don't need the more powerful features.
  • Extensive documentation, and great community support.
  • Used and trusted by internationally recognized companies including Mozilla, Red Hat, Heroku, and Eventbrite.

Chinese:

Django REST framework is a powerful and flexible toolkit for Building Web APIs.

We may want to use the REST framework for some reasons:

  • Web browsing API is a huge availability for developers.
  • Authentication policies include OAuth1a and oau22.
  • Supports the serialization of ORM and non-ORM Data sources.
  • If you do not need more powerful functions, you can use a conventional function-based view.
  • Extensive documentation and good community support.
  • Use and trust by well-known international companies including Mozilla, Red Hat, Heroku, and Eventbrite.

 

Funding

REST framework is a collaboratively (partner location) funded project (Fund project). If you use REST framework already cially we stronugly encourage you to invest (investment) in its continued development (Sustainable development)Signing up for a paid plan. (Register a payment plan)

Every single sign-up helps us make REST framework long-term always Ally sustainable (financial sustainability)

  • Rover.com
  • Sentry
  • Stream
  • Machinalis
  • Rollbar

Descrithanks to all our wonderful sponsors (sponsors), and in particle to our premium backers (quality supporters), Rover, Sentry, Stream, machinbar, and Rollbar.

 

Requirements

REST framework requires the following:

  • Python (2.7, 3.2, 3.3, 3.4, 3.5, 3.6)
  • Django (1.10, 1.11, 2.0 alpha)

The following packages are optional:

  • Coreapi (1.32.0 +)-Schema generation support.
  • Markdown (2.1.0 +)-Markdown support for the browsable API.
  • Django-filter (1.0.1 +)-Filtering support.
  • Django-cripy-forms-Improved HTML display for filtering.
  • Django-guardian (1.1.1 +)-Object level permissions support.

The following software packages are optional:

  • Coreapi (1.32.0 +)-supports mode generation.
  • Markdown (2.1.0 +)-supports Markdown for API browsing.
  • Django-filter (1.0.1 +)-filtering supported.
  • Django-cripy-forms-improved HTML display filtering.
  • Django-guardian (1.1.1 +)-supports object-level permissions.

 

Installation

Install usingpip, Including any optional packages you want...

pip install djangorestframeworkpip install markdown       # Markdown support for the browsable API.pip install django-filter  # Filtering support

... Or clone the project from github.

git clone git@github.com:encode/django-rest-framework.git

Add'rest_framework'To yourINSTALLED_APPSSetting. (remember to add rest_framework to the setting file. Of course, you have to install djangorestframework first)

INSTALLED_APPS = (    ...    'rest_framework',)

If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your rooturls.pyFile.

If you want to use a browsed API, you may also need to add the logon and logout views of the REST framework. Add the following content to your rooturls.pyFile.

urlpatterns = [    ...    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))]

Note that the URL path can be whatever you want, but you must include'rest_framework.urls'With'rest_framework'Namespace. You may leave out the namespace in Django 1.9 +, and REST framework will set it for you.

Note that the URL path can be anything you want, but you must include'rest_framework.urls'And'rest_framework'Namespace. You can omit the namespace in Django 1.9 +, and the REST framework will set it for you.

 

Quickstart

Can't wait to get started? The quickstart guide is the fastest way to get up and running, and building APIs with REST framework.

After talking about a bunch of things, let's get started with a demo and see the results. Official website please see: http://www.django-rest-framework.org/tutorial/quickstart/

 

First, you must first create the django program, and then create the APP. Here I create a quickstart app.

Now sync your database for the first time: Synchronize the database

python manage.py migrate

Create a Super User for login. We'll also create an initial user namedadminWith a passwordpassword123. We'll authenticate as that user later in our example.

python manage.py createsuperuser

 

Serializers

First, we need to define some serialization programs. Create a serializers file in the Quick Start APP to display data.

First up we're re going to define some serializers. Let's create a new module namedtutorial/quickstart/serializers.py That we'll use for our data representations.

from django.contrib.auth.models import User, Groupfrom rest_framework import serializersclass UserSerializer(serializers.HyperlinkedModelSerializer):    class Meta:        model = User        fields = ('url', 'username', 'email', 'groups')class GroupSerializer(serializers.HyperlinkedModelSerializer):    class Meta:        model = Group        fields = ('url', 'name')

Notice that we're using hyperlinked relations in this case,HyperlinkedModelSerializer. You can also use primary key and varous other relationships, but hyperlinking is good RESTful design.

Please note that in this case, we are using a hyperlinkHyperlinkedModelSerializer. You can also use primary keys and other relationships, but hyperlinks are a good RESTful design.

 

Views

Right, we 'd better write some views then. Opentutorial/quickstart/views.pyAnd get typing. Write some views to query data.

from django.contrib.auth.models import User, Groupfrom rest_framework import viewsetsfrom tutorial.quickstart.serializers import UserSerializer, GroupSerializerclass UserViewSet(viewsets.ModelViewSet):    """    API endpoint that allows users to be viewed or edited.    """    queryset = User.objects.all().order_by('-date_joined')    serializer_class = UserSerializerclass GroupViewSet(viewsets.ModelViewSet):    """    API endpoint that allows groups to be viewed or edited.    """    queryset = Group.objects.all()    serializer_class = GroupSerializer

Rather than write multiple views we're re grouping together all the common behavior into classes calledViewSets.

We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.

 

Instead of writing multiple views, we combine all common behaviors into a class named viewset.

If necessary, we can easily break them into separate views, but use viewset to make the view logic well organized and very concise.

 

URLs

Okay, now let's wire up the API URLs. Ontutorial/urls.py...

from django.conf.urls import url, includefrom rest_framework import routersfrom tutorial.quickstart import views
router = routers.DefaultRouter()router.register(r'users', views.UserViewSet)router.register(r'groups', views.GroupViewSet)# Wire up our API using automatic URL routing.# Additionally, we include login URLs for the browsable API.urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))]

Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.

You can use the router class to register this view to automatically generate the api url conf.

Again, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly.

Again, if we need more control over the api url, we can simply pull it to a general class-based view and write the URL conf explicitly.

Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.

Finally, we will include the default logon and logout views for use with browsed APIs. This is optional, but it is useful if your API requires authentication and you want to use a browsed API.

 

Settings

We 'd also like to set a few global settings. We 'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be intutorial/settings.py

We also want to set some global settings. We want to open the page. We hope our API can only be used by the Administrator.

INSTALLED_APPS = (    ...    'rest_framework',)REST_FRAMEWORK = {    'DEFAULT_PERMISSION_CLASSES': [        'rest_framework.permissions.IsAdminUser',    ],    'PAGE_SIZE': 10}

Okay, we're done.

 

:

The main interface, as if nothing ......

Use the superuser logon interface.

Added, deleted, modified, and queried functions.

 

Quick introduction to REST framework components

Next, let's take a look at all the components of the rest framework and learn how they are combined. This is worth learning.

  • 1-Serialization
  • 2-Requests & Responses request & Response
  • 3-Class-based views: Class-based views
  • 4-Authentication & permissions Authentication & permission
  • 5-Relationships & hyperlinked APIs seems to have never been used. Keep it for now, haha ~
  • 6-Viewsets & routers views and routes
  • 7-Schemas & client libraries mode and client library (waiting ~)

Serialization

Here, we will not introduce general serialization. Next we will use ModelSerializersMOdel serialization allows us to write less Code. For more information, see. Django provides the same form and modelform. The REST framework includes the serializer class and model serializer class.

For example, the models file contains a table about the article:

Class Article (models. model): "Document Information" "title = models. charField (max_length = 255, unique = True, db_index = True, verbose_name = "title") source = models. foreignKey ("ArticleSource", verbose_name = "Source") article_type_choices = (0, 'info'), (1, 'video') article_type = models. smallIntegerField (choices = article_type_choices, default = 0) brief = models. textField (max_length = 512, verbose_name = "abstract") head_img = models. charField (max_length = 255) content = models. textField (verbose_name = "Article body") pub_date = models. dateTimeField (verbose_name = "mounting date") offline_date = models. dateTimeField (verbose_name = "dismounting date") status_choices = (0, 'online'), (1, 'offline') status = models. smallIntegerField (choices = status_choices, default = 0, verbose_name = "state") order = models. smallIntegerField (default = 0, verbose_name = "weight", help_text = "to top the article, you can increase the number") comment_num = models. smallIntegerField (default = 0, verbose_name = "comment count") agree_num = models. smallIntegerField (default = 0, verbose_name = "likes") view_num = models. smallIntegerField (default = 0, verbose_name = "viewers") collect_num = models. smallIntegerField (default = 0, verbose_name = "") tags = models. manyToManyField ("Tags", blank = True, verbose_name = "tag") date = models. dateTimeField (auto_now_add = True, verbose_name = "creation date") def _ str _ (self): return "% s-% s" % (self. source, self. title)

Next, you only need to write a serializer to easily obtain the data, and the code looks very concise.

# In serilallzer. the py file can be written like this # If you want to use which model for serialization, you can simply push it like this # If fields wants to get all fields, use "_ all _" # fields to obtain a part of the data. Then, add the serialized model Field in fields to the field from rest_framework.serializers import ModelSerializerclass ArticleSerializer (ModelSerializer ): class Meta: model = models. article fields = ("id", "title", "article_type", "content",) or "_ all __"

  

Now we are getting started, and we will learn more in depth.

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.