1. 程式人生 > 實用技巧 >固定配置

固定配置

目錄

固定的配置檔案

渲染器

 renderer_classes=[JSONRenderer,]
   REST_FRAMEWORK = {
            'DEFAULT_RENDERER_CLASSES': (  # 預設響應渲染類
                'rest_framework.renderers.JSONRenderer',  # json渲染器
                'rest_framework.renderers.BrowsableAPIRenderer',  # 瀏覽API渲染器
            )
        }
    

認證,許可權配置

authentication_classes=[MyAuthentication] # 區域性
permission_classes = [UserPermision]
REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.app_auth.MyAuthentication",]
    'DEFAULT_PERMISSION_CLASSES': [
        'app01.auths.UserPermision',
    ],
}

頻率

'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ),
    'DEFAULT_THROTTLE_RATES': {
        'user': '10/m',
        'anon': '5/m',
    }

過濾

'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)

異常處理

from rest_framework.views import exception_handler
# from luffyapi.utils import response
from .response import APIResponse
from .logger import log


def common_exception_handler(exc, context):
    log.error('view是:%s ,錯誤是%s' % (context['view'].__class__.__name__, str(exc)))
    # context['view']  是TextView的物件,想拿出這個物件對應的類名
    print(context['view'].__class__.__name__)
    ret = exception_handler(exc, context)  # 是Response物件,它內部有個data

    if not ret:  # drf內建處理不了,丟給django 的,我們自己來處理
        # 好多邏輯,更具體的捕獲異常
        if isinstance(exc, KeyError):
            return APIResponse(code=0, msg='key error')

        return APIResponse(code=0, msg='error', result=str(exc))
    else:
        return APIResponse(code=0, msg='error', result=ret.data)

封裝日誌

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
        },
    },
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'console': {
            # 實際開發建議使用WARNING
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {
            # 實際開發建議使用ERROR
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            # 日誌位置,日誌檔名,日誌儲存目錄必須手動建立,注:這裡的檔案路徑要注意BASE_DIR代表的是小luffyapi
            'filename': os.path.join(os.path.dirname(BASE_DIR), "logs", "luffy.log"),
            # 日誌檔案的最大值,這裡我們設定300M
            'maxBytes': 300 * 1024 * 1024,
            # 日誌檔案的數量,設定最大日誌數量為10
            'backupCount': 100,
            # 日誌格式:詳細格式
            'formatter': 'verbose',
            # 檔案內容編碼
            'encoding': 'utf-8'
        },
    },
    # 日誌物件
    'loggers': {
        'django': {
            'handlers': ['console', 'file'],
            'propagate': True,  # 是否讓日誌資訊繼續冒泡給其他的日誌處理系統
        },
    }
}

#另起檔案配置
import logging
# log=logging.getLogger('名字') # 跟配置檔案中loggers日誌物件下的名字對應
log=logging.getLogger('django')

同源策略

# 還要再apps裡面註冊corsheaders
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)
CORS_ALLOW_HEADERS = (
    'authorization',
    'content-type',
)

media和auth表擴充套件設定

AUTH_USER_MODEL = 'user.User'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

jwt認證的配置

JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),  # 過期時限7天
}

限制手機發送簡訊的頻率設定

class SMSThrottling(SimpleRateThrottle):
    scope = 'sms'

    def get_cache_key(self, request, view):
        telephone = request.query_params.get('telephone')
        return self.cache_format % {'scope': self.scope, 'ident': telephone}
    
    
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES': {
        'sms': '1/m'  # key要跟類中的scop對應
    }
}

django-redis的配置

## django-redis的配置
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100}
            # "PASSWORD": "123",
        }
    }
}