Writing in the front

There are more than one tool for building Restful interfaces under Django (like Tastypie), but DRF is the best known of the moment.

Django REST Framework is a powerful and flexible Django toolkit that provides a convenient REST API development framework with the following features:

  • Beautiful API Web interface.

  • Excellent third-party plug-in support.

  • Community activity is good.

  • Version update speed is fast.

The text start

Get started quickly on a Django backend project with a Restful style

First, environmental preparation

  1. To install Python, you can download and install Python from the official website based on your PC environment

    A MAC can install Brew Install Python using the brew command

  2. Install PipenV to configure your virtual environment pipenv

    For MAC, brew Install Pipenv can be installed using the brew command

  3. You can also install Pipenv before installing Python

$ pipenvUsage: pipenv [OPTIONS] COMMAND [ARGS]... Options: --where Output project home information. --venv Output virtualenv information. --py Output Python interpreter information. --envs Output Environment Variable options. --rm Remove the virtualenv. --bare Minimal output. --completion  Output completion (to be eval'd). --man Display manpage. --three / --two Use Python 3/2 when creating virtualenv. --python TEXT Specify which version of Python virtualenv should use. --site-packages Enable site-packages for the virtualenv. --version Show the version and exit. -h, --help Show this message and exit. Usage Examples: Create a new project using Python 3.7, Specifically:   $Pipenv - python 3.7

   Remove project virtualenv (inferred from current directory):
   $ pipenv --rm

   Install all dependencies for a project (including dev):
   $ pipenv install --dev

   Create a lockfile containing pre-releases:
   $ pipenv lock --pre

   Show a graph of your installed dependencies:
   $ pipenv graph

   Check your installed dependencies for security vulnerabilities:
   $ pipenv check

   Install a local setup.py into your virtual environment/Pipfile:
   $ pipenv install -e .

   Use a lower-level pip command:
   $ pipenv run pip freeze

Commands:
  check      Checks for security vulnerabilities and against PEP 508 markers
             provided in Pipfile.
  clean      Uninstalls all packages not specified in Pipfile.lock.
  graph      Displays currently–installed dependency graph information.
  install    Installs provided packages and adds them to Pipfile, or (if no
             packages are given), installs all packages from Pipfile.
  lock       Generates Pipfile.lock.
  open       View a given module in your editor.
  run        Spawns a command installed into the virtualenv.
  scripts    Displays the shortcuts in the (optional) [scripts] section of 
             Pipfile. 
  shell      Spawns a shell within the virtualenv.
  sync       Installs all packages specified in Pipfile.lock.
  uninstall  Un-installs a provided package and removes it from Pipfile.
Copy the code

2. Create a project

  1. You can quickly build projects using PyCharm in conjunction with Pipenv that you just configured

  1. Build the completed project

  1. An error was encountered at startup

The solution is simply to add import OS at the beginning of settings.py

  1. Startup Screenshot

Note: You can also visit http://127.0.0.1:8000/ to view the startup success

Configure Django Restframework

1. Install dependencies

pipenv install djangorestframework markdown django-filter
Copy the code

2. Add the ‘rest_framework’ item to INSTALLED_APPS.

INSTALLED_APPS = [
    ...
    'rest_framework',
]
Copy the code

3. Perform initial configuration

Project Settings

#Create an initialization database
$ python manage.py migrate

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

#Create the super user amdin/admin
python manage.py createsuperuser

Copy the code

Added files demo/serializers. Py

# new demo/serializers. Py

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')

Copy the code

New file demo/views.py

# new demo/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) :
    """ API path that allows users to view or edit. "" "
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet) :
    """ API path that allows groups to view or edit. "" "
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

Copy the code

Modify the file demo/urls.py

# modified demo/urls. Py

from django.contrib import admin
from django.urls import path

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

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

urlpatterns = [
    url(r'^', include(router.urls)),
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls')))Copy the code

Modify the demo/Settings. Py

# new file at the bottom

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAdminUser',].'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination'.'PAGE_SIZE': 10
}
Copy the code

4. Last step

Restart the service (it should automatically update the code if it was started previously)

The browser visits http://127.0.0.1:8000/ and logs in to the account (the created superuser). The result is shown below

Command test


python manage.py runserver

$  curl -H 'Accept: application/json; indent=4'-u admin: admin at http://127.0.0.1:8000/{" users ":" http://127.0.0.1:8000/users/ ", "groups" : "http://127.0.0.1:8000/groups/"}Copy the code

5. Project Catalog

Let’s have a bucket for the project

$tree | grep -v pyc. ├ ─ ─ Pipfile ├ ─ ─ Pipfile. Lock ├ ─ ─ demo │ ├ ─ ─ just set py │ ├ ─ ─ asgi. Py │ ├ ─ ─ serializers. Py │ ├ ─ ─ Settings. Py │ ├ ─ ─ Urls. Py │ ├ ─ ─ views. Py │ └ ─ ─ wsgi. Py ├ ─ ─ the manage. PyCopy the code

conclusion

What DRF can do, we can do directly with Django, why use DRF?

Django does, but you need to spend more time developing and testing it. Since it takes so much extra time and is not as good as anyone else’s, why not stand on the shoulders of giants. DRF is a proven and reliable implementation of REST apis, allowing for checks and validations that you might not have considered. Finally, if you use Python, you want to improve your development efficiency; If you want to build wheels, you can open the DRF plugin for everyone to learn and communicate

The resources

  • Django
  • Django REST Framework Chinese documentation