Django REST framework 入门

2,391 阅读2分钟

写在前面

在Django下构建Restful接口的工具不止一个(比如Tastypie),但是当下最出名的就是DRF。

Django REST framework 一个强大灵活的Django工具包,提供了便捷的 REST API 开发框架,拥有以下特性:

  • 美观的 API web 界面。

  • 优秀的第三方插件支持。

  • 社区活跃度好。

  • 版本更新速度快。

正文开始

快速开始一个基于Django且拥有Restful风格的后端项目吧

一、环境准备

  1. 安装 Python 具体可以根据自己的电脑环境按照官网下载安装 Python

    mac 可以使用 brew 命令安装 brew install python

  2. 安装 pipenv 配置你的虚拟环境 Pipenv

    mac 可以使用 brew 命令安装 brew install pipenv

  3. 你也可以先装 Pipenv 在安装 python,反正怎么简单怎么来 下面贴一下常见的pipenv的命令

$ pipenv
Usage: 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.

二、创建项目

  1. 使用 PyCharm 结合刚配置的 Pipenv 可以快速构建项目

image.png

  1. 构建完成后的项目

image.png

  1. 这里启动遇到一个错误

image.png

解决方式只需要在 settings.py 的开头新增 import os

  1. 启动成功截图

image.png

备注: 同时可以访问 http://127.0.0.1:8000/ 查看启动成功效果

三、配置 Django Restframework

1. 安装依赖

pipenv install djangorestframework markdown django-filter

2. 在INSTALLED_APPS中添加 'rest_framework' 项。

INSTALLED_APPS = [
    ...
    'rest_framework',
]

3. 初始化配置

项目设置

# 创建初始化数据库
$ 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

# 创建超级用户 (注意设置用户名密码)amdin/admin
python manage.py createsuperuser

新增文件 demo/serializers.py

# 新增 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')

新增文件 demo/views.py

# 新增 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路径。
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    允许组查看或编辑的API路径。
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

修改文件 demo/urls.py

# 修改 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'))
]

修改 demo/settings.py

# 文件最底部新增

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAdminUser',

    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

4. 最后一步

重启服务 (如果之前已经启动应该会自动更新代码)

浏览器访问 http://127.0.0.1:8000/ 并登录账号(创建的超级用户)得到结果如下图

image.png

命令测试


python manage.py runserver

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

5. 项目目录

来张项目的全家桶

$ tree  | grep -v pyc
.
├── Pipfile
├── Pipfile.lock
├── demo
│   ├── __init__.py
│   ├── asgi.py
│   ├── serializers.py
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
├── manage.py

总结

DRF能做的,我们直接用django一样的能实现,为什么还需要使用 DRF 呢?

其实Django能实现只不过你需要花更多的时间去开发 测试。既然需要额外的付出那么多时间而且还没有别人的好用,为什么不站在巨人的肩膀上呢。DRF就相当于是经过验证的可靠的rest api的实现方式,有些你没考虑到的检查和校验它都帮你考虑到了。最后既然用了python肯定就是希望开发效率有所提升;如果渴望造轮子,你可以开放DRF的插件供大家学习交流~~~

参考资料