使用rest_framework写api接口的一些注意事项(axios发送ajax请求)
1. 類(lèi)繼承GenericAPIView,定義queryset
印象深刻的事:
由于原來(lái)對(duì)于繼承關(guān)系不太清楚,寫(xiě)接口 APIView/泛指GenericAPIView不太關(guān)注queryset
沒(méi)有設(shè)置渲染器:默認(rèn) [JSONRenderer,BrowsableAPIRenderer]
BrowsableAPIRenderer,內(nèi)部檢查當(dāng)前視圖函數(shù)是否有 get_queryset,如有則會(huì)調(diào)用。未設(shè)置,則斷言異常。
2. 所有視圖都有功能:添加到配置文件
比如統(tǒng)一渲染器,解析器等
3. URL統(tǒng)一規(guī)則
url后加不加/等,都要統(tǒng)一
4. 序列化?
- 簡(jiǎn)單:fk/o2o/choice -> source
- 復(fù)雜:m2m/gfk -> SerializerMethodField
在序列化類(lèi)中定義字段時(shí),對(duì)于一些簡(jiǎn)單的外鍵、一對(duì)一字段或choice字段可以使用source方法獲取想要的值
而復(fù)雜一些的多對(duì)多字段等可以使用自定義方法
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
跨域請(qǐng)求可以通過(guò)中間件添加相應(yīng)的響應(yīng)頭,一些參數(shù)還可以寫(xiě)到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發(fā)送ajax請(qǐng)求
首先要下載axios
npm install axios --save
然后在main.js中導(dǎo)入,并使用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"的意思是后續(xù)的axios發(fā)送請(qǐng)求時(shí)請(qǐng)求頭中都會(huì)帶有Content-Type='application/json',ajax中也能做相應(yīng)的設(shè)置,如下
$.ajaxSetup({beforeSend: function(xhr, settings) {xhr.setRequestHeader("Content-Type", "application/json");}
}); 使用
init(){// 發(fā)送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)})
} 通過(guò)axios.request方法發(fā)起ajax請(qǐng)求,參數(shù)url是發(fā)送的地址,method是發(fā)送方法,params是url中的參數(shù),如果要發(fā)送請(qǐng)求體中的參數(shù)則使用data
then相當(dāng)于ajax中的success,catch相當(dāng)于error
轉(zhuǎn)載于:https://www.cnblogs.com/weiwu1578/articles/8909014.html
總結(jié)
以上是生活随笔為你收集整理的使用rest_framework写api接口的一些注意事项(axios发送ajax请求)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 米勒罗宾素性测试(Miller–Rabi
- 下一篇: qq个性签名非主流男生