drf框架

  • 新建一个项目:

    # 进入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'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值