django 配置swagger 以及登录登出,以及自定义参数

直接贴代码

settings.py 

"""
Django settings for dynamic_create_db_table project.

Generated by 'django-admin startproject' using Django 2.1.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

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.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*y5&((+#l!!-ow_e^4vd4+l@uj9q0jr!)&nru!!x&!*7dvc)^g'

# 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',
    'apps.dynamic_create_and_update_db_table.apps.DynamicCreateAndUpdateDbTableConfig',
    'rest_framework',
    'rest_framework_swagger'
]

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 = 'dynamic_create_db_table.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 = 'dynamic_create_db_table.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME':"dynamic_db",
        'USER':"root",
        'PASSWORD':'160216',
        'HOST':'*******',
        'PORT':'3306',
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/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',
    },
]

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser',
    ),
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema',
}
SWAGGER_SETTINGS = {
    # 基础样式
    # 'SECURITY_DEFINITIONS': {
    #     "basic": {
    #         'type': 'basic'
    #     }
    # },
    'USE_SESSION_AUTH': True,
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'authorization'
        }
    },
    # "app_name":'rest_framework',
    # 如果需要登录才能够查看接口文档, 登录的链接使用restframework自带的.
    # 'LOGIN_URL': '/api/v1/login/',
    # 'LOGOUT_URL': 'rest_framework:logout',
    # 'DOC_EXPANSION': None,
    # 'SHOW_REQUEST_HEADERS':True,
    # 'USE_SESSION_AUTH': True,
    # 'DOC_EXPANSION': 'list',
    # 接口文档中方法列表以首字母升序排列
    'APIS_SORTER': 'alpha',
    # 如果支持json提交, 则接口文档中包含json输入框
    'JSON_EDITOR': True,
    # 方法列表字母排序
    'OPERATIONS_SORTER': 'alpha',
    'VALIDATOR_URL': None,
}
# 配置对应的url
LOGIN_URL = 'accounts/login'
LOGOUT_URL = 'accounts/logout'
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

自定义参数 网上找的,看懂的话可以自己实现

params.py

from rest_framework.schemas import SchemaGenerator
from rest_framework.schemas.generators import LinkNode, insert_into
from rest_framework.renderers import *
from rest_framework_swagger import renderers
from rest_framework.response import Response
from rest_framework.decorators import APIView
from rest_framework.permissions import AllowAny,IsAuthenticated,IsAuthenticatedOrReadOnly
from django.http import JsonResponse


class MySchemaGenerator(SchemaGenerator):

    def get_links(self, request=None):
        links = LinkNode()

        paths = []
        view_endpoints = []
        for path, method, callback in self.endpoints:
            view = self.create_view(callback, method, request)
            path = self.coerce_path(path, method, view)
            paths.append(path)
            view_endpoints.append((path, method, view))

        # Only generate the path prefix for paths that will be included
        if not paths:
            return None
        prefix = self.determine_path_prefix(paths)

        for path, method, view in view_endpoints:
            if not self.has_view_permissions(path, method, view):
                continue
            link = view.schema.get_link(path, method, base_url=self.url)
            # 添加下面这一行方便在views编写过程中自定义参数.
            link._fields += self.get_core_fields(view)

            subpath = path[len(prefix):]
            keys = self.get_keys(subpath, method, view)

            # from rest_framework.schemas.generators import LinkNode, insert_into
            insert_into(links, keys, link)

        return links

    # 从类中取出我们自定义的参数, 交给swagger 以生成接口文档.
    def get_core_fields(self, view):
        return getattr(view, 'coreapi_fields', ())


class SwaggerSchemaView(APIView):
    _ignore_model_permissions = True
    exclude_from_schema = True

    #permission_classes = [AllowAny]
    # 此处涉及最终展示页面权限问题,如果不需要认证,则使用AllowAny,这里需要权限认证,因此使用IsAuthenticated
    permission_classes = [IsAuthenticated]
    # from rest_framework.renderers import *
    renderer_classes = [
        CoreJSONRenderer,
        renderers.OpenAPIRenderer,
        renderers.SwaggerUIRenderer
    ]

    def get(self, request):
        # 此处的titile和description属性是最终页面最上端展示的标题和描述
        generator = MySchemaGenerator(title='API说明文档',description='''接口测试、说明文档''')

        schema = generator.get_schema(request=request)

        # from rest_framework.response import Response
        return Response(schema)


def DocParam(name="default", location="query",required=True, description=None, type="string",
             *args, **kwargs):
    return coreapi.Field(name=name, location=location,
                         required=required, description=description,
                         type=type)

urls.py

#coding=utf-8
from django.urls import path,include
from . import views
app_name = "login"
from apps.utils.params import SwaggerSchemaView


urlpatterns = [
    path('login/',views.Login.as_view()),
    path('docs/accounts/login',views.LoginView.as_view(), name='login'),
    path('docs/', SwaggerSchemaView.as_view(),name="docs"),
    path('api-auth/',include('rest_framework.urls',namespace='rest_framework')),
]

  views.py

from rest_framework.views import APIView
from .models import Campany,UserProfile
from rest_framework.response import Response
from apps.utils.params import DocParam

from django.shortcuts import HttpResponse,HttpResponseRedirect
# Create your views here.

from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
class Login(APIView):
    '''
        post:
            测试测试测试
        '''
    coreapi_fields = (
        DocParam(name="id", location='query', description='测试接口'),
        # DocParam(name="AUTHORIZATION", location='header', description='token'),
        DocParam(name="AUTHORIZATION", location='query', description='token'),
    )

    def get(self,request,format=None):
        campany = Campany.objects.get(id=1)
        name = campany.name
        id = campany.id
        data = {
            "id":id,
            "name":name
        }
        print(data)
        return Response(data)


    def post(self,request):
        print(request.query_params)
        return Response({"data":"success"})


class LoginView(APIView):
    def get(self,request):
        userprofile = UserProfile.objects.get(id=1)
        auth_login(request,userprofile.user)
        return HttpResponseRedirect('/docs')


class LogoutView(APIView):
    def get(self,request):
        auth_logout(request)
        return HttpResponseRedirect('/docs')

 models.py

# code=utf-8
from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Campany(models.Model):
    name=models.CharField(max_length=12,default="default")
    s_data = models.IntegerField(default=0)
    def to_dict(self):
        data_dict = dict(name=self.name)
        return data_dict

    def __str__(self):
        return self.name
    class Meta:
        # unique_together = (("campaign", "name", "status"),)
        verbose_name = "公司"
        # verbose_name_plural = "推广单元管理"
        db_table = "campany"

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')

    class Meta:
        verbose_name="User Profile"
    def __str__(self):
        return self.user.__str__()

 django 配置swagger 以及登录登出,以及自定义参数_第1张图片

django 配置swagger 以及登录登出,以及自定义参数_第2张图片

django 配置swagger 以及登录登出,以及自定义参数_第3张图片

django 配置swagger 以及登录登出,以及自定义参数_第4张图片

你可能感兴趣的:(django 配置swagger 以及登录登出,以及自定义参数)