使用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

浙公网安备 33010602011771号