栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Bottle Py:为jQuery AJAX请求启用CORS

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Bottle Py:为jQuery AJAX请求启用CORS

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

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

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

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

import bottlefrom bottle import response# the decoratordef 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_corsapp = bottle.app()@app.route('/cors', method=['OPTIONS', 'GET'])@enable_corsdef lvambience():    response.headers['Content-type'] = 'application/json'    return '[1]'app.run(port=8001)

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

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

skip
参数来避免针对每个路由使用此处理程序。)以下示例与上述示例相对应:

import bottlefrom bottle import responseclass 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_corsapp = 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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/436877.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号