McF*_*ane 2 django http-status-code-405 http-options-method
我试图让 OPTIONS 请求与 django 一起工作,但我目前只得到 405。我在这里得到的答案是服务器不处理 OPTIONS 请求。
这是处理请求的视图:
from django.views.generic import View
from piston.utils import coerce_put_post
class TheView(View):
@staticmethod
def find_stuff(params):
...
@staticmethod
def do_stuff(params):
...
@staticmethod
def do_other_stuff(params):
...
@staticmethod
def delete_some_stuff(params):
...
@method_decorator(staff_member_required)
def get(self, request, id):
result = self.find_stuff(id)
return JsonResponse(result)
@method_decorator(staff_member_required)
def post(self, request):
result = self.do_stuff(request.POST)
return JsonResponse(result)
@method_decorator(staff_member_required)
def put(self, request, id):
coerce_put_post(request)
result = self.do_other_stuff(id,request.PUT)
return JsonResponse(result)
@method_decorator(staff_member_required)
def delete(self, request,id):
result = self.delete_some_stuff(id)
return JsonResponse(result)
Run Code Online (Sandbox Code Playgroud)
我正在使用 jQuery 的 $.ajax() 发送请求。这是chrome的开发工具捕获的网络日志:
http://localhost请求头
http://localhosthttp://localhost/bar响应头
http://localhost那么我怎样才能让 django 服务器来处理它呢?
我怀疑该OPTIONS请求正在返回 405 错误,因为options您的视图类中尚未定义处理程序。请注意,Django 不提供默认options处理程序。
这是负责在您的类上调用适当方法的代码(django 源代码):
# snippet from django.views.generic.base.View
http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options', 'trace']
def dispatch(self, request, *args, **kwargs):
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
options是可以在 Django 视图中处理的默认 http 方法之一。如果options尚未定义处理程序,该dispatch方法将返回 405 错误。
这是options方法的一个例子
class TheView(View):
self.allowed_methods = ['get', 'post', 'put', 'delete', 'options']
def options(self, request, id):
response = HttpResponse()
response['allow'] = ','.join([self.allowed_methods])
return response
Run Code Online (Sandbox Code Playgroud)