ajax 启用cors,Bottle Py:为jQuery AJAX请求启用CORS

小编典典

安装一个处理程序而不是一个钩子。

我过去有两种互补的方法:装饰器或Bottle插件。我将向您展示两者,您可以决定它们中的一个(或两者)是否满足您的需求。在这两种情况下,通常的想法是:处理程序在将响应发送回客户端之前先对其进行拦截,然后插入CORS标头,然后继续返回响应。

方法1:按路线安装(装饰器)

当您只想在某些路由上运行处理程序时,最好使用此方法。只需装饰要执行的每条路线即可。这是一个例子:

import bottle

from bottle import response

# the decorator

def enable_cors(fn):

def _enable_cors(*args, **kwargs):

# set CORS headers

response.headers['Access-Control-Allow-Origin'] = '*'

response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'

response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

if bottle.request.method != 'OPTIONS':

# actual request; reply with the actual response

return fn(*args, **kwargs)

return _enable_cors

app = bottle.app()

@app.route('/cors', method=['OPTIONS', 'GET'])

@enable_cors

def lvambience():

response.headers['Content-type'] = 'application/json'

return '[1]'

app.run(port=8001)

方法2:全局安装(瓶插件)

如果希望处理程序在所有或大多数路由上执行,则最好使用此方法。您只需定义一次Bottle插件,Bottle就会在每条路线上自动为您调用它;无需在每一个上指定一个装饰器。(请注意,您可以使用路由的skip参数来避免针对每个路由使用此处理程序。)以下示例与上述示例相对应:

import bottle

from bottle import response

class EnableCors(object):

name = 'enable_cors'

api = 2

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'] = 'GET, POST, PUT, OPTIONS'

response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

if bottle.request.method != 'OPTIONS':

# actual request; reply with the actual response

return fn(*args, **kwargs)

return _enable_cors

app = bottle.app()

@app.route('/cors', method=['OPTIONS', 'GET'])

def lvambience():

response.headers['Content-type'] = 'application/json'

return '[1]'

app.install(EnableCors())

app.run(port=8001)

2020-07-26

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值