使用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.Coursefields = ['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 inprice_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使用它
?
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(){// 發送Ajaxvar that = thisthis.$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
轉載于:https://www.cnblogs.com/weiwu1578/articles/8909014.html
總結
以上是生活随笔為你收集整理的使用rest_framework写api接口的一些注意事项(axios发送ajax请求)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 米勒罗宾素性测试(Miller–Rabi
- 下一篇: (转)搭建企业内部yum仓库(cento