pythondjango

python3.9
Django 3.2
djangorestframework 3.12.4

django

django/DRF(Django REST framework)快速入门,如何在5分钟内创建后端API接口应用、自动生成CURD

gobeegoapipydjangoORMviewtemplateHTMLurl
mvcjspgo template

django/DRF(Django REST framework)快速入门,如何在5分钟内创建后端API接口应用、自动生成CURD
图片引用自知乎@丁果

创建项目

django-admin startproject mysite

运行(后面的ip:端口指定可省略)

python manage.py runserver [0:8000]

目录结构

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py
polls
python manage.py startapp polls

目录结构

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py
    polls/
        __init__.py
        admin.py
        apps.py
        migrations/
            __init__.py
        models.py
        tests.py
        urls.py
        views.py
django
ormpolls/models.py
from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
setting.pyapp
pollsmodelDDLpython
python manage.py makemigrations [polls]
sql
python manage.py sqlmigrate polls 0001
sql
python manage.py migrate
/admin
python manage.py createsuperuser
jsonapi
django

DRF(Django REST framework)

将数据库的东西通过ORM的映射取出来,通过view和serializers文件绑定REST接口,当前端请求时,返回序列化好的json

DRF是Django的超集,去掉了模板的部分,提供了一个REST的接口,同时也提供了满足该接口的代码工作流。同时,在REST的规范下,升级了权限和分页等功能,增加了限流和过滤搜索等功能。

Django的tutorial讲的是Django的ORM、template、url、admin以及Django怎么run起来等基础知识。

而DRF的tutorial讲的是serializers怎么写,view怎么写,在drf中view这一层既可以一个个get、post、从头开始写起,也可以采用抽象程度比较高的viewset去按配置生成。另外还讲了一些drf升级和新增的功能。

django/DRF(Django REST framework)快速入门,如何在5分钟内创建后端API接口应用、自动生成CURD
图片引用自知乎@丁果

modelCURD
django-filter==21.1
django-log-request-id==1.6.0
django-mysql==4.3.0

使用与接入

1.安装

pip install pymysql djangorestframework django-filter
#settings.py的INSTALLED_APPS中添加:

NSTALLED_APPS = [
    ...
    'django_filters',
    'rest_framework',
    'rest_framework.authtoken',
    'rest_framework_filters',
    'app',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
        'rest_framework.permissions.DjangoModelPermissions',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        rest_framework.authentication.BasicAuthentication
        #'app.common.auth.YoozooTokenAuthentication' 自定义认证,
    ),

    'PAGE_SIZE': 15,
    'DEFAULT_PAGINATION_CLASS': 'app.common.page.YoozooPage',
    'PAGINATE_BY_PARAM': 'limit',
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',
                                'rest_framework.filters.SearchFilter',
                                'rest_framework.filters.OrderingFilter'
                                ),
}
_init_.py
import pymysql
pymysql.install_as_MySQLdb()

2.数据库models

from django.db import models

class Test(models.Model):
    name = models.CharField(max_length=20)

3.序列化

from rest_framework import serializers

class TestSerializer(serializers.ModelSerializer):
    class Meta: 
        #与test表对应
        model = Test 
        #取全部字段
        fields = '__all__'

4.过滤filter

from django_filters.rest_framework import FilterSet

class TestFilter(FilterSet):
    class Meta:
        model = Test
        fields = '__all__'

5.视图viewset

from rest_framework import viewsets

class TestViewSet(viewsets.ModelViewSet):
    filter_class = TestFilter
    queryset = Test.objects.all()
    serializer_class = TestSerializer

6.修改url

from django.conf.urls import url, include
from django.contrib import admin
from django.urls import path
from rest_framework import routers
import app.ormrest as orm
import app.views as views

router = routers.DefaultRouter()
router.register(r'test', orm.resapply.ResapplyViewSet)
urlpatterns = [
    #url(r'^admin/', admin.site.urls),
    url(r'^api/', include(router.urls)),
]
CURD/api/test

内建接口文档自动生成

setting.py
REST_FRAMEWORK = {
   ....
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
}
urls.py
from rest_framework.documentation import include_docs_urls

urlpatterns = [
    url(r'^api/v1/docs/', include_docs_urls(title="文档标题", description="描述",permission_classes=[], authentication_classes=[])),
]

这样就可以自动生成文档了。详见Built-in API documentation

依赖或可选的 Package:

  • coreapi Package 是本特性的依赖项,确保安装最新版本哦(2.3.0 或更高版本)
  • pygments Package 编程代码高亮(可选)
  • markdown Package markdown 语法高亮(可选)

命令小结

创建项目

django-admin startproject mysite

运行(后面的ip:端口指定可省略)

python manage.py runserver [0:8000]
polls
python manage.py startapp polls
pollsmodelDDLpython
python manage.py makemigrations [polls]
sql
python manage.py sqlmigrate polls 0001
sql
python manage.py migrate
/admin
python manage.py createsuperuser

引用