如何在此 BOTTLE 派生中启用 CORS class

How to enable CORS in this BOTTLE derivated class

我的 REST Api 将只在 localhost 服务,它使用这个 bottle 代码:

https://github.com/cgiraldo/mininetRest/blob/master/mininet_rest.py

Firefox/Chrome 阻止 Cross-Origin 请求。我必须启用 CORS 才能让服务器传送访问控制响应 header。

代码示例:

class MininetRest(Bottle):

def __init__(self, net):
    super(MininetRest, self).__init__()
    self.net = net
    self.route('/pingall', method='GET', callback=self.pingall)

#how to integrate this in my code?
@hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Authorization, Origin, Accept, Content-Type, X-Requested-With'

def pingall(self):
    self.net.pingAll()

我发现很多代码在 Bottle 中启用 Cors,但没有人处理 bottle class 的派生 class。

你能试试下面的方法吗?

我已经使用 EnableCors class 创建了一个实用程序,如下所示

from bottle import request, response
class EnableCors(object):
    def apply(self, fn, context):
        def _enable_cors(*args, **kwargs):
            # set CORS headers
            response.headers['Access-Control-Allow-Origin'] = '*'
            response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE'
            response.headers['Access-Control-Allow-Headers'] = 'Authorization, Origin, Accept, Content-Type, X-Requested-With'

            if request.method != 'OPTIONS':
                # actual request; reply with the actual response
                return fn(*args, **kwargs)
        return _enable_cors

并使用它(让我们带上你的 class),

from path.to.your_utility import EnableCors
class MininetRest(Bottle):
    def __init__(self, net):
        super(MininetRest, self).__init__()
        self.route('/pingall', method='GET', callback=self.pingall)
        self.install(EnableCors())

当然,您需要查看 Access-Control-* 选项并根据您的要求选择所需的内容。

希望对您有所帮助