[Django Learning] (15) API Interface Documentation Platform_Project Process Analysis_Logger_Authentication_Authorization

1. API interface document platform

The use of API interface documents can not only maintain the interface data well, but also bring convenience to the interface testing work of testers;

We can add routing paths to the global configuration file to generate interface documents

1. Use the docs interface document to maintain the interface

1.1 Specify the Schema used to support coreapi in the global configuration file

    # 指定用于支持coreapi的Schema
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',

1.2 Add a path in the global routing table

from rest_framework.documentation import include_docs_urls
urlpatterns = [
    path('docs/', include_docs_urls(title='接口文档', description='非常友好的接口文档')),
    ]

  Page effect:

 2. Use the swager interface document to maintain the interface

2.1 Be sure to register drf_yasg in the configuration table first, otherwise the page will report an error

INSTALLED_APPS = [
                'drf_yasg',
                    ]

 2.2 Add a path to the global routing table

from rest_framework.documentation import include_docs_urls
schema_view = get_schema_view(
    openapi.Info(
        title="超人 API接口文档平台",  # 必传
        default_version='v1',  # 必传
        description="这是一个美轮美奂的接口文档",
        terms_of_service="http://api.keyou.site",
        contact=openapi.Contact(email="[email protected]"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    # permission_classes=(permissions.AllowAny,),   # 权限类
)
urlpatterns = [
        path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    ]

  Page effect:

 2.3 We can also use the swager document to convert it into json or yaml format

from rest_framework.documentation import include_docs_urls
schema_view = get_schema_view(
    openapi.Info(
        title="超人 API接口文档平台",  # 必传
        default_version='v1',  # 必传
        description="这是一个美轮美奂的接口文档",
        terms_of_service="http://api.keyou.site",
        contact=openapi.Contact(email="[email protected]"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    # permission_classes=(permissions.AllowAny,),   # 权限类
)
urlpatterns = [
        re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    ]

  Page effect:

 3. Use the redoc interface document to maintain the interface

3.1 Be sure to register drf_yasg in the configuration table first, otherwise the page will report an error

INSTALLED_APPS = [
                'drf_yasg',
                    ]

 3.2 Add a path to the global routing table

from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="超哥 API接口文档平台",  # 必传
        default_version='v1',  # 必传
        description="这是一个美轮美奂的接口文档",
        terms_of_service="http://api.keyou.site",
        contact=openapi.Contact(email="[email protected]"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    # permission_classes=(permissions.AllowAny,),   # 权限类
)
urlpatterns = [
    path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),

]

 Page effect:

 2. Logger

Add a logger to the global configuration table

# LOGGING指定日志器的相关配置
LOGGING = {
    # 指定日志版本
    'version': 1,
    # 指定是否禁用其他已存在的日志器
    'disable_existing_loggers': False,
    # 指定日志的输出格式
    'formatters': {
        # 指定普通的日志输出格式
        'simple': {
            'format': '%(asctime)s - [%(levelname)s] - [msg]%(message)s'
        },
        # 指定更详细的日志输出格式
        'verbose': {
            'format': '%(asctime)s - [%(levelname)s] - %(name)s - [msg]%(message)s - [%(filename)s:%(lineno)d ]'
        },
    },
    # 指定日志的过滤器
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    # 定义日志的输出渠道
    'handlers': {
        # 指定控制台日志输出渠道
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        # 指定日志输出的日志配置
        'file': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, "logs/mytest.log"),  # 日志文件的位置
            # 每一个日志文件的最大字节数
            'maxBytes': 100 * 1024 * 1024,
            # 指定日志文件总数
            'backupCount': 10,
            'formatter': 'verbose'
        },
    },
    # 指定日志器
    'loggers': {
        'mytest': {  # 定义了一个名为mytest的日志器
            'handlers': ['console', 'file'],
            'propagate': True,
            'level': 'DEBUG',  # 日志器接收的最低日志级别
        },
    }
}

use logger

# 导入logging模块
import logging
# 制定日志器对象,getLogger需要传递在settings-->LOGGING中,设置的日志器名称,必须要一致
my_logging=logging.getLogger('mytest')
my_logging.info('prijects的视图集类')

The saved log file information is:

 3. Certification

Global Authentication Class

There is a global authentication class in the settings of drf

If the authorization class is not specified, the request interface will not be affected, and the returned data can still be obtained through the normal access interface;

If the authorization class is specified, if you request the interface when you are not logged in, the unauthenticated information will be returned:

Let's create a user

python manage.py createsuperuser

 Set username, email, password

 You can see the created user information in the auth_user table in the database

 

 When calling the interface requires authentication to obtain permissions, but the user does not have authentication, we need to log in

After successful login, you will enter the previously visited page

 Partial authentication class

Some interfaces do not need to be accessed after logging in. For example, the login and registration interface needs to be exposed to users all the time. At this time, it is necessary to define a partial authentication class for the interface view class that requires authentication .

Priority: local authentication class>global authentication class

from rest_framework.authentication import SessionAuthentication,BasicAuthentication
# 定义局部认证类
authentication_classes = [SessionAuthentication,BasicAuthentication]

 

4. Authorization

Global Authorization Class

Specify the global authorization class in the settings of drf

Specify the permission class (the permission that will be granted after the authentication is passed)

The default permission class is AllowAny, which allows all users to access the interface

Specifies that only after logging in, can the access interface be authorized

'DEFAULT_PERMISSION_CLASSES': [
        # 默认的权限类为AllowAny,允许所有用户返回接口
        # 'rest_framework.permissions.AllowAny',
        # 指定只有登录之后,才具有访问接口的权限
        'rest_framework.permissions.IsAuthenticated',
    ],

partial authorization class

Some interfaces do not need to be accessed after logging in. For example, the login registration interface needs to be exposed to users all the time. At this time, it is necessary to define a partial authorization class for the interface view class that requires an authorization class (authorization is required after login authentication )

Priority: local authorization class>global authorization class

from rest_framework.permissions import IsAuthenticated
# 定义局部授权类
permission_classes = [IsAuthenticated]

Guess you like

Origin blog.csdn.net/weixin_43569834/article/details/131797842