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

ron rothman..

32

安装处理程序而不是钩子.

我过去有两种互补方式:decorator或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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值