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)