我正在Django应用程序上工作,我想使用ajax创建多个异步请求到django服务器。如果异步请求少于5个,但对于某些请求,则使用django return 500 (Internal Server Error)
进行请求,它可以很好地工作。如果我发出同步ajax请求,则效果很好。
我发送多个ajax请求的代码:
for (i=2; i <= lastIndex; i++){
pidForm['page_index'] = i;
$.ajax({
type: 'POST',
url: '{% url "search_by_pid" %}',
data: pidForm,
success: function (data) {
console.log(data);
$(data.api_response.bugs).each(function(index, bugs){
var id = bugs.id;
createInnerHtml(id);
});
}
})
}
我的django视图,我在其中发送ajax请求:
def get_bug_by_pid(request):
product_id_form = ProductIdForm()
if request.method == 'GET':
return render(request, 'search_bug_by_pid.html',
{'page_title': 'ProductID', 'product_id_form': product_id_form})
elif request.method == 'POST':
product_id = request.POST['product_id']
if 'page_index' in request.POST:
api_call = ApiCall()
page_index = request.POST['page_index']
api_response = api_call.bug_api_call_by_pid(product_id, page_index)
return JsonResponse({'api_response': api_response,'product_id': product_id})
Internal Server Error: /pid/
Traceback (most recent call last):
File "C:\exception.py", line 34, in inner
response = get_response(request)
File "C:\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\views.py", line 26, in get_bug_by_pid
api_response = api_call.bug_api_call_by_pid(product_id, page_index)
File "api_calls.py", line 33, in bug_api_call_by_pid
return json.loads(r.content)
File "C:\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
有什么想法可以解决问题或做错了什么吗?
答案 0 :(得分:1)
您的问题与您说的ajax请求无关。从您提供的跟踪中,我可以看到您正在django视图中对另一个服务/ URL进行另一个API调用,并且代码已在此处中断。
File "api_calls.py", line 33, in bug_api_call_by_pid
return json.loads(r.content)
通过对远程服务进行如此多的调用,您可能正在对该服务进行DDOS操作,或者远程服务正在限制您的速率并且不发送回有效的JSON。
您可以通过以下任一方法相当简单地解决此问题:
if response.status_code == 200:
return response.json()
我希望这会有所帮助