我正在使用Django Rest框架实现API。我想Python可以像Ruby一样发送POST参数吗?
例如:
POST /api/end_point/
params = { 'user_id': [1,2,3] }
# In controller, we get an array of user_id:
user_ids = params[:user_id] # [1,2,3]
答案 0 :(得分:1)
在POST
中有多种方法可以解决这个问题,具体取决于您实际上要做的事情。
如果您打算通过Serializer
数据传递此数据,则应使用django-rest-framework
。使用序列化程序和Serializer
POST
,您可以通过json
或form
提供Serializer
数据。
Serializer Field
文档:http://www.django-rest-framework.org/api-guide/serializers/
ListField
文档:http://www.django-rest-framework.org/api-guide/fields/
具体来说,您需要查看from rest_framework import serializers
from rest_framework.decorators import api_view
class ItemSerializer(serializers.Serializer):
"""Your Custom Serializer"""
# Gets a list of Integers
user_ids = serializers.ListField(child=serializers.IntegerField())
@api_view(['POST'])
def item_list(request):
item_serializer = ItemSerializer(data=request.data)
item_serializer.is_valid(raise_exception=True)
user_ids = item_serializer.data['user_ids']
# etc ...
。
它没有经过测试,但你会想要的东西:
$(document).ready(function(){
var url = utils.getUrlVars() && utils.getUrlVars().url;
if (!url) throw "error - no URL was found. set 'url' in query string.";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "blob";
oReq.onreadystatechange = function(e) {
if (oReq.readyState == 4 && oReq.status == 200) {
console.log('xhr success');
success(e);
} else if (oReq.readyState == 4 && oReq.status != 200){
console.log('xhr error');
error(e);
}
}
var success = function() {
var blob = oReq.response;
var sha1 = CryptoJS.algo.SHA1.create();
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onload = function(e) {
var arrbuffer = e.target.result.slice(0, e.target.result.byteLength);
var bytes = CryptoJS.enc.u8array.parse(new Uint8Array(arrbuffer));
sha1.update(bytes);
var sha1res = sha1.finalize().toString(CryptoJS.enc.Hex);
// print results
console.log('sha1 - success', sha1res);
}
};
var error = function(){
IJavaScriptImplementer.onError(JSON.stringify(error));
IJavaScriptImplementer.log(JSON.stringify(error));
}
oReq.send(null);
});