python 具有跨源资源共享的瓶子(CORS)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 具有跨源资源共享的瓶子(CORS)相关的知识,希望对你有一定的参考价值。

"""
Example of setting up CORS with Bottle.py.
"""

from bottle import Bottle, request, response, run
app = Bottle()

@app.hook('after_request')
def enable_cors():
    """
    You need to add some headers to each request.
    Don't use the wildcard '*' for Access-Control-Allow-Origin in production.
    """
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

@app.route('/examples', method=['OPTIONS', 'GET'])
def examples():
    """
    If you are using something like Spine.js you'll need to
    handle requests for the OPTIONS method. I haven't found a
    DRY way to handle this yet. I tried setting up a hook for before_request,
    but was unsuccessful for now.
    """
    if request.method == 'OPTIONS':
        return {}
    else:
        return {'examples': [{
            'id': 1,
            'name': 'Foo'},{
            'id': 2,
            'name': 'Bar'}
        ]}


if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("--host", dest="host", default="localhost",
                      help="hostname or ip address", metavar="host")
    parser.add_option("--port", dest="port", default=8080,
                      help="port number", metavar="port")
    (options, args) = parser.parse_args()
    run(app, host=options.host, port=int(options.port))

以上是关于python 具有跨源资源共享的瓶子(CORS)的主要内容,如果未能解决你的问题,请参考以下文章

Fusion Tables 不支持 CORS(跨源资源共享)?

跨源资源共享(CORS)概念实现(用Spring)起源介绍

即使存在所有 CORS 标头,也存在跨源资源共享问题

markdown Web字体的CORS跨源资源共享问题

CORS(跨源资源共享)https 不工作(IIS 托管 WCF 休息启用端点)

基于 jQuery AJAX SOAP 的 Web 服务和 CORS(跨源资源共享)[关闭]