Chinese version of Django-REST-framework

Posted by stakes on Sun, 30 Jun 2019 01:18:17 +0200

quick get start

Here we create a simple API for administrators to view and edit user and group information.

Project Settings

Create a new django project named tutorial and create an APP named quickstart:

# new directory
mkdir tutorial
cd tutorial

# New Virtual Environment
virtualenv env
source env/bin/activate  # Windows uses `env Scripts activate`

# Installing dependencies in a virtual environment
pip install django
pip install djangorestframework

# New projects
django-admin.py startproject tutorial .  # Notice the following'. '
cd tutorial
django-admin.py startapp quickstart
cd ..

Create tables using the following commands:

python manage.py migrate

Then create an administrator with the user name admin password123:

python manage.py createsuperuser

After the above settings are completed, enter the APP directory to write the code.

serialize

First, we create a file tutorial/quickstart/serializers.py to write serialization-related code:

from django.contrib.auth.models import User, Group
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

Note that in the above code we used Hyperlink ModelSerializer to establish hyperlink relationships, you can also use primary keys or other relationships, but hyperlinking is a good RESTful design.

Views

Now let's write the view file tutorial/quickstart/views.py:

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    //View and edit user interface
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    //View and Edit Group Interface
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

We encapsulate many common operations in the class ViewSets so that we don't have to write duplicate code. Of course, you can write views according to your own needs, but using ViewSets can keep the view code simple and logical.

URLs

Next, write tutorial/urls.py:

from django.conf.urls import url, include
from rest_framework import routers
from tutorial.quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# Use URL routing to manage our API
# Additionally add login-related URL s
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Because we use ViewSets, we can automatically generate URL configuration information by using the Router class.

Again, if you need to configure the URL more autonomously, you can use regular class views and write the URL configuration explicitly.

Finally, we added the default login and logout view to use when browsing the API. This is an optional option, but it is very useful if you want to use authentication when browsing the API.

Settings

We also need some global settings. We want to enable paging and only administrators can access, edit tutorial/settings.py:

INSTALLED_APPS = (
    ...
    'rest_framework',
)

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

So far, we have completed all our work.

test

Now let's test our API and enter in the terminal:

python ./manage.py runserver

Now we can use command-line tools to access API s, such as curl:

curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "email": "admin@example.com",
            "groups": [],
            "url": "http://127.0.0.1:8000/users/1/",
            "username": "admin"
        },
        {
            "email": "tom@example.com",
            "groups": [                ],
            "url": "http://127.0.0.1:8000/users/2/",
            "username": "tom"
        }
    ]
}

Or httpie

http -a admin:password123 http://127.0.0.1:8000/users/

HTTP/1.1 200 OK
...
{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "email": "admin@example.com",
            "groups": [],
            "url": "http://localhost:8000/users/1/",
            "username": "paul"
        },
        {
            "email": "tom@example.com",
            "groups": [                ],
            "url": "http://127.0.0.1:8000/users/2/",
            "username": "tom"
        }
    ]
}

Or open the browser directly:If you use a browser, make sure you have logged in using the login function in the upper right corner.

Great, it's that simple!

Topics: Django Python pip curl