-
安装drf依赖包
pip install djangorestframework==3.12.1 pip install djangorestframework-jwt==1.11.0 pip install django_filter==2.4.0
-
跨域配置
INSTALLED_APPS = [ ... 'corsheaders', # 跨域 ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # 跨域 ... ] # 允许所有网站可以访问项目接口 CORS_ORIGIN_ALLOW_ALL = True # CORS跨域请求白名单设置, 只有在白名单中的网站才能访问接口 # CORS_ORIGIN_WHITELIST = ( # 'http://127.0.0.1:8080', # 'http://localhost:8080', # 'http://127.0.0.1:8081', # 'http://localhost:8081', # 'http://0.0.0.0:8080', # 'http://mysyl.com:8080', # ) # 允许携带cookie # CORS_ALLOW_CREDENTIALS = True
-
配置drf的settings
# 过滤器 # 1,安装 django-filter # 2,注册应用 # 3,配置settings, 在view里配置可过滤的字段 # 4,使用 查询字符串携带过滤信息 REST_FRAMEWORK = { # 文档报错: AttributeError: ‘AutoSchema’ object has no attribute ‘get_link’ # 用下面的设置可以解决 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema', # 默认设置是: # 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.openapi.AutoSchema', # 异常处理器 # 'EXCEPTION_HANDLER': 'user.utils.exception_handler', # 非drf的原始的认证方式是: 账号密码->cookie(session) # drf用户认证方式主要是使用 jwt 认证, 账号密码 -> jwt 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', # 使用session时的认证器, drfweb页面的认证方式 # 'rest_framework.authentication.BasicAuthentication' # 提交表单时的认证器 ], # 权限配置, 顺序靠上的严格, 全部通过才有权限 'DEFAULT_PERMISSION_CLASSES': [ # 职员可以访问() is_staff=True 'rest_framework.permissions.IsAdminUser', # 管理员可以访问 # 认证用户可以访问 is_active=True, 登录的人 'rest_framework.permissions.IsAuthenticated', # 认证用户可以访问, 否则只能请求安全方法 SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') 'rest_framework.permissions.IsAuthenticatedOrReadOnly', # 所有用户都可以访问 'rest_framework.permissions.AllowAny', ], # 限流 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle'
drf框架配置
最新推荐文章于 2024-04-25 11:04:15 发布