我试图让OPTIONS请求与django一起工作,但我目前只获得405。 我得到here的答案是服务器不处理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)
我使用jQuery的$ .ajax()发送请求。这是chrome的开发工具捕获的网络日志:
http://localhost
请求标题
http://localhost
http://localhost/bar
响应标题
http://localhost
那么如何让django服务器来处理呢?
答案 0 :(得分:4)
我怀疑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)
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