一, 安装 drf-yasg:
由于 django-REST-swagger 已经废弃了
所以引入了 drf-yasg
pip install drf-yasg
安装 install drf-yasg 库
https://github.com/axnsan12/drf-yasg
GitHub 主页
二, 工程的目录结构:
- demo/settings.py:
- import os
- # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
- BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- # Quick-start development settings - unsuitable for production
- # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
- # SECURITY WARNING: keep the secret key used in production secret!
- SECRET_KEY = '[email protected]^k!pw$6kx*0$+9#%[email protected]*h^+xs%5&(+q*b181&o$)l'
- # SECURITY WARNING: don't run with debug turned on in production!
- DEBUG = True
- ALLOWED_HOSTS = []
- # Application definition
- INSTALLED_APPS = [
- 'django.contrib.admin',
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- 'product.apps.ProductConfig',
- 'xadmin',
- 'crispy_forms',
- 'reversion',
- # 添加 django-xadmin
- 'import_export',
- # 导入导出
- 'ckeditor',
- 'ckeditor_uploader',
- # 富文本编辑器
- 'rest_framework',
- # django-REST-framework
- 'drf_yasg',
- # drf-yasg
- ]
- MIDDLEWARE = [
- 'django.middleware.security.SecurityMiddleware',
- 'django.contrib.sessions.middleware.SessionMiddleware',
- 'django.middleware.common.CommonMiddleware',
- 'django.middleware.csrf.CsrfViewMiddleware',
- 'django.contrib.auth.middleware.AuthenticationMiddleware',
- 'django.contrib.messages.middleware.MessageMiddleware',
- 'django.middleware.clickjacking.XFrameOptionsMiddleware',
- ]
- ROOT_URLCONF = 'demo.urls'
- TEMPLATES = [
- {
- 'BACKEND': 'django.template.backends.django.DjangoTemplates',
- 'DIRS': [os.path.join(BASE_DIR, 'templates')]
- ,
- 'APP_DIRS': True,
- 'OPTIONS': {
- 'context_processors': [
- 'django.template.context_processors.debug',
- 'django.template.context_processors.request',
- 'django.contrib.auth.context_processors.auth',
- 'django.contrib.messages.context_processors.messages',
- ],
- },
- },
- ]
- WSGI_APPLICATION = 'demo.wsgi.application'
- # Database
- # https://docs.djangoproject.com/en/2.2/ref/settings/#databases
- DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.mysql',
- 'NAME': 'demo',
- 'HOST': '192.168.1.106',
- 'PORT': '3306',
- 'USER': 'root',
- 'PASSWORD': '[email protected]',
- }
- }
- # MySQL 数据库配置
- # Password validation
- # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
- AUTH_PASSWORD_VALIDATORS = [
- {
- 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
- },
- {
- 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
- },
- {
- 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
- },
- {
- 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
- },
- ]
- # Internationalization
- # https://docs.djangoproject.com/en/2.2/topics/i18n/
- LANGUAGE_CODE = 'zh-hans'
- # 简体中文界面
- TIME_ZONE = 'Asia/Shanghai'
- # 亚洲 / 上海时区
- USE_I18N = True
- USE_L10N = True
- USE_TZ = False
- # 不使用国际标准时间
- # Static files (CSS, JavaScript, Images)
- # https://docs.djangoproject.com/en/2.2/howto/static-files/
- STATIC_URL = '/static/'
- STATIC_ROOT = os.path.join(BASE_DIR, 'static')
- # 定义静态文件的目录
- MEDIA_URL = '/media/'
- MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
- # 定义图片存放的目录
- IMPORT_EXPORT_USE_TRANSACTIONS = True
- # 在导入数据时使用数据库事务, 默认 False
- CKEDITOR_BASEPATH = os.path.join(BASE_DIR, "/static/ckeditor/ckeditor/")
- # 配置 CKEditor 的模板路径
- CKEDITOR_CONFIGS = {
- 'default': {
- 'toolbar': 'full',
- 'height': 300,
- 'width': 900,
- },
- }
- # 使用默认的主题名称
- CKEDITOR_UPLOAD_PATH = "uploads/"
- # 配置图片存储的目录, 不用创建
- # 默认使用 MEDIA_ROOT, 所以路径是 media/uploads
- CKEDITOR_RESTRICT_BY_DATE = True
- # 按年 / 月 / 日的目录存储图片
- CKEDITOR_BROWSE_SHOW_DIRS = True
- # 按存储在其中的目录对图像进行分组, 并按日期排序
- CKEDITOR_IMAGE_BACKEND = "pillow"
- # 启用缩略图
- REST_FRAMEWORK = {
- 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
- 'PAGE_SIZE': 5
- # 分页
- }
- demo/urls.py:
- import xadmin
- from django.conf import settings
- from django.conf.urls import url
- from django.conf.urls.static import static
- from django.urls import path, include
- from rest_framework import routers, permissions
- from drf_yasg.views import get_schema_view
- from drf_yasg import openapi
- from product import views
- router = routers.DefaultRouter()
- router.register('product_info', views.ProductInfoViewSet)
- schema_view = get_schema_view(
- openapi.Info(
- title="测试工程 API",
- default_version='v1.0',
- description="测试工程接口文档",
- terms_of_service="https://www.google.com/policies/terms/",
- contact=openapi.Contact(email="[email protected]"),
- license=openapi.License(name="BSD License"),
- ),
- public=True,
- permission_classes=(permissions.AllowAny,),
- )
- urlpatterns = [
- path('admin/', xadmin.site.urls),
- path('ckeditor/', include('ckeditor_uploader.urls')),
- # 添加 CKEditor 的 URL 映射
- path('api/', include(router.urls)),
- path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
- # 配置 django-REST-framwork API 路由
- url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
- path('swagger', 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'),
- # 配置 drf-yasg 路由
- ]
- urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- # 配置图片文件 url 转发
- product/admin.py:
- import xadmin
- # Register your models here.
- from import_export import resources
- from xadmin import views
- from product.models import ProductInfo
- class ProductInfoResource(resources.ModelResource):
- class Meta:
- model = ProductInfo
- skip_unchanged = True
- # 导入数据时, 如果该条数据未修改过, 则会忽略
- report_skipped = True
- # 在导入预览页面中显示跳过的记录
- import_id_fields = ('id',)
- # 对象标识的默认字段是 id, 您可以选择在导入时设置哪些字段用作 id
- fields = (
- 'id',
- 'product_name',
- 'product_picture',
- 'product_describe',
- 'product_manager',
- )
- # 白名单
- exclude = (
- 'product_detail',
- 'create_time',
- 'update_time',
- )
- # 黑名单
- class ProductInfoAdmin(object):
- list_display = [
- 'id',
- 'product_name',
- 'product_picture',
- 'product_describe',
- 'product_manager',
- 'product_detail',
- 'create_time',
- 'update_time',
- ]
- # 要显示的字段列表
- ordering = ['id']
- # 按照 id 顺序排列, 如果是倒序 - id
- search_fields = ['product_name', 'product_manager']
- # 要搜索的字段
- list_filter = ['product_name', 'create_time', 'update_time']
- # 要筛选的字段
- show_detail_fields = ['product_name', 'product_detail']
- # 要展示详情的字段
- list_editable = ['product_name', 'product_describe', 'product_manager']
- # 列表可直接修改的字段
- list_per_page = 10
- # 分页
- # model_icon = 'fa fa-laptop'
- # 配置模型图标, 也可以在 GlobalSetting 里面配置
- import_export_args = {
- 'import_resource_class': ProductInfoResource,
- # 'export_resource_class': ProductInfoResource,
- }
- # 配置导入按钮
- class BaseSetting(object):
- enable_themes = True
- use_bootswatch = True
- # 开启主题自由切换
- class GlobalSetting(object):
- global_search_models = [ProductInfo]
- # 配置全局搜索选项, 默认搜索组, 用户, 日志记录
- site_title = "测试平台"
- # 标题
- site_footer = "测试部"
- # 页脚
- menu_style = "accordion"
- # 左侧菜单收缩功能
- apps_icons = {
- "product": "fa fa-music",
- }
- # 配置应用图标, 即一级菜单图标
- global_models_icon = {
- ProductInfo: "fa fa-film",
- }
- # 配置模型图标, 即二级菜单图标
- xadmin.site.register(ProductInfo, ProductInfoAdmin)
- # 注册模型
- xadmin.site.register(views.BaseAdminView, BaseSetting)
- xadmin.site.register(views.CommAdminView, GlobalSetting)
- product/apps.py:
- from django.apps import AppConfig
- class ProductConfig(AppConfig):
- name = 'product'
- verbose_name = '产品管理'
- product/models.py:
- from ckeditor_uploader.fields import RichTextUploadingField
- from django.db import models
- # Create your models here.
- class ProductInfo(models.Model):
- # 产品表
- product_name = models.CharField(max_length=32, verbose_name="产品名称", default="请输入产品名称")
- # 产品名称
- product_picture = models.ImageField(blank=True,
- null=True,
- upload_to="pictures/%Y%m%d",
- max_length=255,
- verbose_name="产品图片")
- # 产品图片, 数据库里面存储的是图片的相对路径
- product_describe = models.TextField(max_length=255, verbose_name="产品描述", default="请输入产品描述")
- # 产品描述
- product_manager = models.CharField(max_length=11, verbose_name="产品经理", default="请输入产品经理名字")
- # 产品经理
- product_detail = RichTextUploadingField(verbose_name="产品详情", default="", blank=True, null=True)
- # 产品详情, 带有上传图片功能的富文本编辑器
- create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
- # 创建时间
- update_time = models.DateTimeField(auto_now=True, blank=True, null=True, verbose_name="修改时间")
- # 修改时间
- class Meta:
- db_table = 'product_info'
- # 设置表名, 默认表名是: 应用名称_模型类名
- # 带有应用名的表名太长了
- verbose_name = '产品列表'
- verbose_name_plural = "产品列表"
- def __str__(self):
- return self.product_name
- product/serializers.py:
- from rest_framework import serializers
- from product.models import ProductInfo
- class ProductInfoSerializer(serializers.HyperlinkedModelSerializer):
- # 序列化
- class Meta:
- model = ProductInfo
- fields = "__all__"
- product/views.py:
- # Create your views here.
- from rest_framework import viewsets
- from product.models import ProductInfo
- from product.serializers import ProductInfoSerializer
- class ProductInfoViewSet(viewsets.ModelViewSet):
- """
- retrieve:
- 返回一组 (查)
- list:
- 返回所有组 (查)
- create:
- 创建新组 (增)
- delete:
- 删除现有的一组 (删)
- partial_update:
- 更新现有组中的一个或多个字段 (改: 部分更改)
- update:
- 更新一组 (改: 全部更改)
- """
- queryset = ProductInfo.objects.all()
- serializer_class = ProductInfoSerializer
三, 启动服务:
python manage.py collectstatic
复制静态资源文件
python manage.py makemigrations
激活模型
python manage.py migrate
迁移
python manage.py createsuperuser
创建超级管理员
python manage.py runserver
启动服务
四, Swagger API 文档:
http://127.0.0.1:8000/redoc/
http://127.0.0.1:8000/swagger
来源: http://www.bubuko.com/infodetail-3166944.html