【问题标题】:PUT request not working with web2py?PUT 请求不适用于 web2py?
【发布时间】:2013-09-19 03:56:48
【问题描述】:

我们在 web2py 上的 restfull web 服务中的跨域资源共享 (CORS) 实施遇到了一些问题。

我们尝试在 web2py 的服务器端实现 CORS,如下所示:(https://groups.google.com/forum/#!msg/web2py/kSUtyNcUQGI/qfiIqfUiWLwJ)

我们在 models/0.py 中添加了以下内容,(在控制器中实际的 restfull api 处理程序之前更新响应头)

=================================

if request.env.http_origin:
    response.headers['Access-Control-Allow-Origin'] = request.env.http_origin
    response.headers['Access-Control-Allow-Origin'] = "*"
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['Access-Control-Max-Age'] = 86400

    if request.env.request_method == 'OPTIONS':
        if request.env.http_access_control_request_method:
            print request.env.http_access_control_request_method
            response.headers['Access-Control-Allow-Methods'] = request.env.http_access_control_request_method
            if request.env.http_access_control_request_headers:
                response.headers['Access-Control-Allow-Headers'] = request.env.http_access_control_request_headers

===========================

RESTful POST & GET 现在可以工作了 但 PUT 和 DELETE 不是因为预检 http OPTIONS 请求被 web2py 拒绝为“400 BAD REQUEST”

例如,当使用本地网页的 ajax 调用调用 restful webservice 时, 我们在 NetBeans 日志中收到以下错误消息。

加载资源失败:服务器响应状态为 400 (错误请求)(10:46:36:182 | 错误,网络)在 127.0.0.1:8000/test/default/api/entries/2.json 加载资源失败:Origin localhost:8383 is not allowed by 访问控制允许来源。 (10:46:36:183 | 错误,网络)在 127.0.0.1:8000/test/default /api/entries/2.json XMLHttpRequest 无法加载 127.0.0.1:8000/test/default /api/entries/2.json。起源 Access-Control-Allow-Origin 不允许 localhost:8383。 (10:46:36:183 | 错误,javascript)在 www/page/test.html

【问题讨论】:

    标签: python web2py


    【解决方案1】:

    您可以添加以下行:

    response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"

    【讨论】:

      【解决方案2】:

      这是一个非常古老的问题,但我只是设法解决了完全相同的问题。就我而言,问题出在控制器上;我必须在任何操作之前添加以下包装器:

      def CORS(f):
          """
          Enables CORS for any action
          """
          def wrapper(*args, **kwds):
              if request.env.http_origin and request.env.request_method == 'OPTIONS':
                  response.view = 'generic.json'
                  return dict()
              return f(*args, **kwds)
          return wrapper
      

      然后在你的控制器中直接写

      @CORS
      def whatever():
          do_stuff
          return dict(stuff)
      

      【讨论】:

        猜你喜欢
        • 2017-06-16
        • 2019-04-11
        • 1970-01-01
        • 2015-04-10
        • 1970-01-01
        • 1970-01-01
        • 2019-04-27
        • 1970-01-01
        相关资源
        最近更新 更多