如何在这个BOTTLE派生类中启用CORS

时间:2018-02-15 16:17:55

标签: python cors bottle mininet

我的REST Api将仅在localhost中使用,它使用此瓶代码:

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

Firefox / Chrome阻止跨源请求。我必须启用CORS才能让服务器提供访问控制响应头。

代码示例:

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()

我发现许多代码可以在瓶子中启用Cors,但没有人处理瓶子类的派生类。

1 个答案:

答案 0 :(得分:0)

你能尝试以下方法吗?

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

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

并使用它(让我们上课),

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 - * 选项,并选择您的要求所需的内容。

希望这会有所帮助