-
新建一个项目:
# 进入git工程目录 django-admin startproject demo_drf
-
使用pycharm打开新建的项目
-
安装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', # 用户登陆认证方式 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', # 使用session时的认证器, drfweb页面的认证方式 # 'rest_framework.authentication.BasicAuthentication' # 提交表单时的认证器 ], # 权限配置, 顺序靠上的严格 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.IsAdminUser', # 管理员可以访问 'rest_framework.permissions.IsAuthenticated', # 认证用户可以访问 # 'rest_framework.permissions.IsAuthenticatedOrReadOnly', # 认证用户可以访问, 否则只能读取 # 'rest_framework.permissions.AllowAny', # 所有用户都可以访问 ], # 限流 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle', ], # 限流策略 'DEFAULT_THROTTLE_RATES': { 'user': '1000/hour'
drf框架
最新推荐文章于 2024-03-17 20:12:15 发布