zoukankan      html  css  js  c++  java
  • 使用rest_framework写api接口的一些注意事项(axios发送ajax请求)

    使用rest_framework写api接口的一些注意事项(axios发送ajax请求)

    1. 类继承GenericAPIView,定义queryset

    印象深刻的事:
    由于原来对于继承关系不太清楚,写接口 APIView/泛指GenericAPIView不太关注queryset
    没有设置渲染器:默认 [JSONRenderer,BrowsableAPIRenderer]
    BrowsableAPIRenderer,内部检查当前视图函数是否有 get_queryset,如有则会调用。未设置,则断言异常。

    2. 所有视图都有功能:添加到配置文件

    比如统一渲染器,解析器等

    3. URL统一规则

    url后加不加/等,都要统一

    4. 序列化 

    - 简单:fk/o2o/choice -> source
    - 复杂:m2m/gfk -> SerializerMethodField

    在序列化类中定义字段时,对于一些简单的外键、一对一字段或choice字段可以使用source方法获取想要的值

    而复杂一些的多对多字段等可以使用自定义方法

    复制代码
    class CourseSerializer(ModelSerializer):
        category = serializers.CharField(source='sub_category.name')
        xx = serializers.CharField(source='get_course_type_display')
        price_policy = serializers.SerializerMethodField()
        class Meta:
            model = models.Course
            fields = ['id', 'name','category','xx','price_policy']
    
        def get_price_policy(self, obj):
            price_policy_list = obj.degreecourse_price_policy.all()
            return [{'id': row.id, 'price': row.price, 'period': row.get_valid_period_display()} for row in
                    price_policy_list]
    复制代码

    5. cors

    跨域请求可以通过中间件添加相应的响应头,一些参数还可以写到settings中

    复制代码
    class Cors(MiddlewareMixin):
        def process_response(self, request, response):
            response['Access-Control-Allow-Origin'] = ','.join(settings.CORS_ORIGIN_LIST)
            if request.method == 'OPTIONS':
                response['Access-Control-Allow-Methods'] =  ','.join(settings.CORS_METHOD_LIST)
                response['Access-Control-Allow-Headers'] = ','.join(settings.CORS_HEADER_LIST)
                response['Access-Control-Allow-Credentials'] = 'true'
    
            return response
    复制代码

    使用axios发送ajax请求

    首先要下载axios

    npm install axios --save

    然后在main.js中导入,并使用Vue.prototype.axios=axios使this.axios=axios方法,让我们可以在后面使用this.axios使用它

    复制代码
    import Vue from 'vue'
    import App from './App'
    import router from './router'
    import store from './store/store'
    import axios from 'axios'
    
    Vue.prototype.$store = store
    Vue.prototype.$axios = axios
    axios.defaults.headers['Content-Type'] = "application/json"
    
    Vue.config.productionTip = false
    复制代码

    这里axios.defaults.headers['Content-Type'] = "application/json"的意思是后续的axios发送请求时请求头中都会带有Content-Type='application/json',ajax中也能做相应的设置,如下

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("Content-Type", "application/json");
        }
    });

    使用

    复制代码
    init(){
      // 发送Ajax
      var that = this
      this.$axios.request({
        url: this.$store.state.apiList.course,
        method:'GET',
        params:{
          course_type:1
        }
      }).then(function (arg) {
        console.log('then',arg)
        that.courseList =arg.data.data
      }).catch(function (arg) {
        console.log('catch',arg.response)
      })
    }
    复制代码

    通过axios.request方法发起ajax请求,参数url是发送的地址,method是发送方法,params是url中的参数,如果要发送请求体中的参数则使用data

    then相当于ajax中的success,catch相当于error

  • 相关阅读:
    javascript操作cookie实例
    由浅到深了解JavaScript类[转过来的收藏]
    [MySql识记]create utf8 database
    关于游戏开发中的A*/Astar的寻路算法的问题
    对与list<>泛型的一些操作方法
    浅谈完美时空的小气
    npgsql连接postgresql数据库
    哪个美女最漂亮,自己写的js图片自适应切换
    javascript改变this指针
    [图解] 你不知道的 JavaScript “this”(转)
  • 原文地址:https://www.cnblogs.com/xyhh/p/10861253.html
Copyright © 2011-2022 走看看