11.8luffycity(3)

2018-11-8 19:11:49

打算过几天回学校!

越努力越幸运~!永远不要高估自己!

 

做一下笔记,等路飞项目做完放上github连接

 

1. 复杂的跨域

class CORSMiddleware(MiddlewareMixin):
    """
    为了解决跨域问题 添加响应头!定义了这个中间件,在settings中配置了
    """
    def process_response(self,request,response):
        # 添加响应头

        # 允许你的域名来获取我的数据
        response['Access-Control-Allow-Origin'] = "*"

        # 允许你携带Content-Type请求头
        # response['Access-Control-Allow-Headers'] = "Content-Type"

        # 允许你发送DELETE,PUT
        # response['Access-Control-Allow-Methods'] = "DELETE,PUT"

        response['Access-Control-Allow-Origin'] = "*"
    # 这是复杂的跨域,浏览器给两次请求,
    # 解决办法就是 报啥错,请求头缺啥,在response中添加啥 if request.method == "OPTIONS": response['Access-Control-Allow-Headers'] = "Content-Type" response['Access-Control-Allow-Methods'] = "PUT,DELETE" return response

2. vue 的拦截器

这个拦截器是vue自带的

在main.js中配置

// router自带的拦截器
router.beforeEach(function (to, from, next) {
  if(to.meta.requireAuth){
    // 要去的url只有登陆成功后才能访问
    if (store.state.token) {
      next()
    } else {
      next({name: 'login',query: {backUrl: to.fullPath}})
    }
  }else{
    next()
  }
})

router/index.js中部分代码

就是在你想拦截的路由中加上 

meta:{
requireAuth:true
}

例如

  routes: [
    {
      path: '/index',
      name: 'index',
      component: Index
    },
    {
      path: '/course',
      name: 'course',
      component: Course
    },
    {
      path: '/detail/:id',
      name: 'detail',
      component: Detail
    },
    {
      path: '/micro',
      name: 'micro',
      component: Micro,
      // 需要登录后才能访问
        meta:{
        requireAuth:true
      }
    },
    {
      path: '/news',
      name: 'news',
      component: News,
        // 需要登录后才能访问
        meta:{
        requireAuth:true
      }
    },
        {
      path: '/login',
      name: 'login',
      component: Login
    },
  ],
  mode:'history'
})

3.使用了rest_framework的认证组件

auth.py

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from app01 import models


class LuffyAuth(BaseAuthentication):
    """
    使用rest_framework自带的认证组件,自己的类继承BaseAuthentication,重写父类方法
    使用的时候直接写个列表就好
    authentication_classes = [LuffyAuth, ]
    """
    def authenticate(self, request):
        token = request.query_params.get('token')
        obj = models.UserToken.objects.filter(token=token).first()
        if not obj:
            raise AuthenticationFailed({'code': 1001, 'error': '认证失败'})
        return (obj.user.user, obj)

然后是组件的使用views.py

class MicroView(APIView):
    # 使用写好的认证组件
    authentication_classes = [LuffyAuth, ]

    def get(self, request, *args, **kwargs):
        ret = {'code': 1000, 'title': '微职位'}
        return Response(ret)

4. 创建一个随机字符串的方法 也就是 创建一个随机token的方法

import uuid

uid = str(uuid.uuid4())

其他的也没什么啦!

贴上笔记! 还有笔记回顾好多都是面试题!有空的时候整理一下!!

s9day106

内容回顾:
    1. 你理解的Http协议?
        - 建立在tcp之上
        - 一次请求一次响应然后断开连接(无状态、短连接)
        - 请求和响应
            发送:请求头\r\n\r\n请求体
                  host:www.luffy.com\r\ncontent-type:application/json\r\n\r\n请求体
            响应:响应头\r\n\r\n响应体
                  ...
    2. django请求生命周期
        
    3. wsgi
        
    4. django中间件是什么?
        
    5. 使用中间件做过什么?
        - 内置
            - csrf
            - session
        - 自定义
            - 登录认证
            - 权限
            - cors
    6. 中间件中有多少个方法?
        5个
    
    7. FBV和CBV是什么?以及优缺点。
    
    8. rest api 
        
    9. django rest framework框架
        
    10. 视图常见的继承
        from rest_framework.views import APIView # *
        from rest_framework.generics import GenericAPIView
        from rest_framework.viewsets import GenericViewSet # as_view
        from rest_framework.viewsets import ModelViewSet # *
    
    11. 如何实现的访问频率控制?
        匿名用户:无法控制,因为用户可以换代理IP
            {
                192.168.1.1:[1521223123.232, 1521223122.232, 1521223121.232],
                192.168.1.2:[1521223123.232, 1521223122.232, 1521223121.232],
                192.168.1.3:[1521223123.232, 1521223122.232, 1521223121.232],
                192.168.1.4:[1521223123.232, 1521223122.232, 1521223121.232],
                192.168.1.5:[1521223123.232, 1521223122.232, 1521223121.232],
                192.168.1.6:[1521223123.232, 1521223122.232, 1521223121.232],
            }
        
        
        登录用户:如果有很多账号,也无法限制
            {
                alex:[1521223123.232, 1521223122.232, 1521223121.232],
                eric:[1521223123.232, 1521223122.232, 1521223121.232],
            }
        
        参考源码:from rest_framework.throttling import SimpleRateThrottle
        
    12. 序列化
        - source
        - method 
    
    
    
今日内容:
    1. 示例
        - 推荐课程
        - 用户登录
        - 拦截器
        
        
        VUE:
            - 课程列表:this.$axios + this 
            - 课程详细:this.$axios + this 
            - 用户登录:
                - this.$axios
                - this 
                - 跨域简单和复杂请求
                - vuex做全局变量
                - vuex-cookies 
            - 微职位 
                - 拦截器
                - 携带token 
            
            PS: api可以同一放在store中保存
            
        API:
            - 课程列表 
                - 序列化:source='get_level_display'
            - 课程详细:
                - 序列化:source='get_level_display'
                - 序列化:method
            - 用户登录 
                - update_or_create
            - 微职位 
                - 认证组件 
            
            关联组件:
                - 版本
                - 解析器
                - 渲染器
                - 序列化 
                - 认证组件 
                - 视图 
                - 路由 
            
            
    2. django组件:contenttype
        组件的作用:可以通过两个字段让表和N张表创建FK关系
        
        
        表结构:
            from django.db import models
            from django.contrib.contenttypes.models import ContentType

            from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation


            class DegreeCourse(models.Model):
                """学位课程"""
                name = models.CharField(max_length=128, unique=True)
                course_img = models.CharField(max_length=255, verbose_name="缩略图")
                brief = models.TextField(verbose_name="学位课程简介", )


            class Course(models.Model):
                """专题课程"""
                name = models.CharField(max_length=128, unique=True)
                course_img = models.CharField(max_length=255)

                # 不会在数据库生成列,只用于帮助你进行查询
                policy_list = GenericRelation("PricePolicy")


            class PricePolicy(models.Model):
                """价格与有课程效期表"""
                content_type = models.ForeignKey(ContentType)  # 关联course or degree_course
                object_id = models.PositiveIntegerField()

                #不会在数据库生成列,只用于帮助你进行添加和查询
                content_object = GenericForeignKey('content_type', 'object_id')


                valid_period_choices = (
                    (1, '1天'),
                    (3, '3天'),
                    (7, '1周'), (14, '2周'),
                    (30, '1个月'),
                    (60, '2个月'),
                    (90, '3个月'),
                    (180, '6个月'), (210, '12个月'),
                    (540, '18个月'), (720, '24个月'),
                )
                valid_period = models.SmallIntegerField(choices=valid_period_choices)
                price = models.FloatField()

        使用:
            # 1.在价格策略表中添加一条数据
            # models.PricePolicy.objects.create(
            #     valid_period=7,
            #     price=6.6,
            #     content_type=ContentType.objects.get(model='course'),
            #     object_id=1
            # )

            # models.PricePolicy.objects.create(
            #     valid_period=14,
            #     price=9.9,
            #     content_object=models.Course.objects.get(id=1)
            # )

            # 2. 根据某个价格策略对象,找到他对应的表和数据,如:管理课程名称
            # price = models.PricePolicy.objects.get(id=2)
            # print(price.content_object.name) # 自动帮你找到

            # 3.找到某个课程关联的所有价格策略
            # obj = models.Course.objects.get(id=1)
            # for item in obj.policy_list.all():
            #     print(item.id,item.valid_period,item.price)
            #
        
    3. 表结构 
    
        明天说
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

 

转载于:https://www.cnblogs.com/zhen1996/p/9931394.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值