1、配置环境
安装django,版本3.2
安装djangorestframework, 版本3.12.4
安装drf-yasg2, 版本1.19.4
安装命令:
pip install django
pip install djangorestframework
pip install drf-yasg2
pip list 查看所有安装的python包
2、创建项目
python mamage.py startproject 项目名称
3、创建App
python manage.py startapp app名称
4、注册已经安装的python包、创建的App
配置项目里的 urls.py 文件来加载 the schema_view
from django.contrib import admin from django.urls import path, include, re_path from drf_yasg2 import openapi from drf_yasg2.views import get_schema_view from rest_framework import permissions from iii import testdb # 配置 drf_yasg2 schema_view = get_schema_view( openapi.Info( title="Nmos API", default_version='v1', description="Welcome to the world of Tweet", terms_of_service="https://www.tweet.org", contact=openapi.Contact(email="demo@tweet.org"), license=openapi.License(name="Awesome IP"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ re_path(r'^doc(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), # <-- 这里 path('doc/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), # <-- 这里 path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), # <-- 这里 # path('admin/', admin.site.urls), # 路由分发 path("app01/", include("app01.urls")), path("app02/", include("app02.urls")), # path('testAdd/', testdb.testAdd), # path('testShow/', testdb.testShow), ]
5、编写数据模型
from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=32) price = models.DecimalField(max_digits=5, decimal_places=2) pub_date = models.DateField() publish = models.ForeignKey("Publish", on_delete=models.CASCADE) # authors = models.ManyToManyField("Author") class Publish(models.Model): name = models.CharField(max_length=32) city = models.CharField(max_length=64) email = models.EmailField() class Author(models.Model): name = models.CharField(max_length=32) age = models.SmallIntegerField() # au_detail = models.OneToOneField("AuthorDetail", on_delete=models.CASCADE) class AuthorDetail(models.Model): gender_choices = ( (0, "女"), (1, "男"), (2, "保密"), ) gender = models.SmallIntegerField(choices=gender_choices) tel = models.CharField(max_length=32) addr = models.CharField(max_length=64) birthday = models.DateField()
6、生成表格
python manage.py makemigrations # 检查表结构是否有所变化
python manage.py migrate # 创建表结构