使用 django 的内置服务器处理 OPTIONS 请求

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
  • 请求方法:选项
  • 状态代码:405 方法不允许

请求头

  • 接受/
  • 接受编码:gzip,deflate,sdch
  • 接受语言: de,en-US;q=0.8,en;q=0.6
  • 访问控制请求头:接受、来源、内容类型
  • 访问控制请求方法:PUT
  • 缓存控制:无缓存
  • 连接:保持连接
  • 主持人:富
  • 产地http://localhost
  • 编译指示:无缓存
  • 推荐人http://localhost/bar
  • 用户代理:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36

响应头

  • 访问控制允许凭据:true
  • Access-Control-Allow-Headers : Content-Type, Pragma, Cache-Control
  • 访问控制允许方法:POST、GET、OPTIONS、PUT、DELETE
  • 访问控制允许来源http://localhost
  • 允许:发布、获取、选项、放置、删除
  • 内容类型:文本/html;字符集=utf-8
  • 日期: 2013 年 8 月 9 日星期五 09:39:41 GMT
  • 服务器:WSGIServer/0.1 Python/2.7.4

那么我怎样才能让 django 服务器来处理它呢?

Der*_*wok 6

我怀疑该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)

  • 没关系。这只是一些参数错误。它现在有效。非常感谢! (2认同)