Flask-CORS使用

Flask-CORS跨域请求

简单用法

from flask import Flask

from flask_cors import CORS

app = Flask(__name__)

CORS(app)

@app.route("/")

def helloWorld():

  return "Hello, cross-origin-world!

特定资源的CORS

可以将特定的资源最为字典传入resources,将路径映射到一组选项,

注意:由于多个正则表达式可能匹配一个资源,所以首先按长度(从最长到最短)对正则表达式排序,以便于尝试匹配最特定的正则表达式。

app = Flask(__name__)

cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

@app.route("/api/v1/users")

def list_users():

  return "user example"

通过装饰器指定特定的资源CORS

只需在对Flask的`@ app.route(..)`的调用下方 添加`@cross_origin()`,即可在给定路线上使用CORS。

@app.route("/")

@cross_origin()

def helloWorld():

  return "Hello, cross-origin-world!"

将CORS与Cookie一起使用

默认情况下,由于Flask-CORS具有潜在的安全隐患,因此它不允许跨站点提交Cookie。如果您希望启用跨站点Cookie,则可能希望添加某种 CSRF 保护,以确保您和用户的安全。

要允许跨源发出Cookie或经过身份验证的请求,只需将`supports_credentials`选项设置为True即可。例如

from flask import Flask, session

from flask_cors import CORS

app = Flask(__name__)

CORS(app, supports_credentials=True)

@app.route("/")

def helloWorld():

  return "Hello, %s" % session['username']

将CORS与蓝图一起使用

Flask-CORS开箱即用的支持蓝图。只需将一个蓝图实例传递给CORS扩展,一切都将正常工作。

api_v1 = Blueprint('API_v1', __name__)

CORS(api_v1) # enable CORS on the API_v1 blue print

@api_v1.route("/api/v1/users/")

def list_users():

    '''

        Since the path matches the regular expression r'/api/*', this resource

        automatically has CORS headers set. The expected result is as follows:

        $ curl --include -X GET http://127.0.0.1:5000/api/v1/users/ \

            --header Origin:www.examplesite.com

        HTTP/1.0 200 OK

        Access-Control-Allow-Headers: Content-Type

        Access-Control-Allow-Origin: *

        Content-Length: 21

        Content-Type: application/json

        Date: Sat, 09 Aug 2014 00:26:41 GMT

        Server: Werkzeug/0.9.4 Python/2.7.8

        {

            "success": true

        }

    '''

    return jsonify(user="joe")

@api_v1.route("/api/v1/users/create", methods=['POST'])

def create_user():

    '''

        Since the path matches the regular expression r'/api/*', this resource

        automatically has CORS headers set.

        Browsers will first make a preflight request to verify that the resource

        allows cross-origin POSTs with a JSON Content-Type, which can be simulated

        as:

        $ curl --include -X OPTIONS http://127.0.0.1:5000/api/v1/users/create \

            --header Access-Control-Request-Method:POST \

            --header Access-Control-Request-Headers:Content-Type \

            --header Origin:www.examplesite.com

        >> HTTP/1.0 200 OK

        Content-Type: text/html; charset=utf-8

        Allow: POST, OPTIONS

        Access-Control-Allow-Origin: *

        Access-Control-Allow-Headers: Content-Type

        Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT

        Content-Length: 0

        Server: Werkzeug/0.9.6 Python/2.7.9

        Date: Sat, 31 Jan 2015 22:25:22 GMT

        $ curl --include -X POST http://127.0.0.1:5000/api/v1/users/create \

            --header Content-Type:application/json \

            --header Origin:www.examplesite.com

        >> HTTP/1.0 200 OK

        Content-Type: application/json

        Content-Length: 21

        Access-Control-Allow-Origin: *

        Server: Werkzeug/0.9.6 Python/2.7.9

        Date: Sat, 31 Jan 2015 22:25:04 GMT

        {

          "success": true

        }

    '''

    return jsonify(success=True)

public_routes = Blueprint('public', __name__)

@public_routes.route("/")

def helloWorld():

    '''

        Since the path '/' does not match the regular expression r'/api/*',

        this route does not have CORS headers set.

    '''

    return '''<h1>Hello CORS!</h1> Read about my spec at the

<a href="http://www.w3.org/TR/cors/">W3</a> Or, checkout my documentation

on <a href="https://github.com/corydolphin/flask-cors">Github</a>'''

logging.basicConfig(level=logging.INFO)

app = Flask('FlaskCorsBlueprintBasedExample')

app.register_blueprint(api_v1)

app.register_blueprint(public_routes)

if __name__ == "__main__":

    app.run(debug=True)

例子

使用CORS扩展

# One of the simplest configurations. Exposes all resources matching /api/* to

# CORS and allows the Content-Type header, which is necessary to POST JSON

# cross origin.

CORS(app, resources=r'/api/*')

@app.route("/")

def helloWorld():

    """

        Since the path '/' does not match the regular expression r'/api/*',

        this route does not have CORS headers set.

    """

    return '''

<html>

    <h1>Hello CORS!</h1>

    <h3> End to end editable example with jquery! </h3>

    <a class="jsbin-embed" href="http://jsbin.com/zazitas/embed?js,console">JS Bin on jsbin.com</a>

    <script src="//static.jsbin.com/js/embed.min.js?3.35.12"></script>

</html>

'''

@app.route("/api/v1/users/")

def list_users():

    """

        Since the path matches the regular expression r'/api/*', this resource

        automatically has CORS headers set. The expected result is as follows:

        $ curl --include -X GET http://127.0.0.1:5000/api/v1/users/ \

            --header Origin:www.examplesite.com

        HTTP/1.0 200 OK

        Access-Control-Allow-Headers: Content-Type

        Access-Control-Allow-Origin: *

        Content-Length: 21

        Content-Type: application/json

        Date: Sat, 09 Aug 2014 00:26:41 GMT

        Server: Werkzeug/0.9.4 Python/2.7.8

        {

            "success": true

        }

    """

    return jsonify(user="joe")

@app.route("/api/v1/users/create", methods=['POST'])

def create_user():

    """

        Since the path matches the regular expression r'/api/*', this resource

        automatically has CORS headers set.

        Browsers will first make a preflight request to verify that the resource

        allows cross-origin POSTs with a JSON Content-Type, which can be simulated

        as:

        $ curl --include -X OPTIONS http://127.0.0.1:5000/api/v1/users/create \

            --header Access-Control-Request-Method:POST \

            --header Access-Control-Request-Headers:Content-Type \

            --header Origin:www.examplesite.com

        >> HTTP/1.0 200 OK

        Content-Type: text/html; charset=utf-8

        Allow: POST, OPTIONS

        Access-Control-Allow-Origin: *

        Access-Control-Allow-Headers: Content-Type

        Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT

        Content-Length: 0

        Server: Werkzeug/0.9.6 Python/2.7.9

        Date: Sat, 31 Jan 2015 22:25:22 GMT

        $ curl --include -X POST http://127.0.0.1:5000/api/v1/users/create \

            --header Content-Type:application/json \

            --header Origin:www.examplesite.com

        >> HTTP/1.0 200 OK

        Content-Type: application/json

        Content-Length: 21

        Access-Control-Allow-Origin: *

        Server: Werkzeug/0.9.6 Python/2.7.9

        Date: Sat, 31 Jan 2015 22:25:04 GMT

        {

          "success": true

        }

    """

    return jsonify(success=True)

@app.route("/api/exception")

def get_exception():

    """

        Since the path matches the regular expression r'/api/*', this resource

        automatically has CORS headers set.

        Browsers will first make a preflight request to verify that the resource

        allows cross-origin POSTs with a JSON Content-Type, which can be simulated

        as:

        $ curl --include -X OPTIONS http://127.0.0.1:5000/exception \

            --header Access-Control-Request-Method:POST \

            --header Access-Control-Request-Headers:Content-Type \

            --header Origin:www.examplesite.com

        >> HTTP/1.0 200 OK

        Content-Type: text/html; charset=utf-8

        Allow: POST, OPTIONS

        Access-Control-Allow-Origin: *

        Access-Control-Allow-Headers: Content-Type

        Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT

        Content-Length: 0

        Server: Werkzeug/0.9.6 Python/2.7.9

        Date: Sat, 31 Jan 2015 22:25:22 GMT

    """

    raise Exception("example")

@app.errorhandler(500)

def server_error(e):

    logging.exception('An error occurred during a request. %s', e)

    return "An internal error occured", 500

if __name__ == "__main__":

    app.run(debug=True)

使用cross_origin装饰器

@app.route("/", methods=['GET'])

@cross_origin()

def helloWorld():

    '''

        This view has CORS enabled for all domains, representing the simplest

        configuration of view-based decoration. The expected result is as

        follows:

        $ curl --include -X GET http://127.0.0.1:5000/ \

            --header Origin:www.examplesite.com

        >> HTTP/1.0 200 OK

        Content-Type: text/html; charset=utf-8

        Content-Length: 184

        Access-Control-Allow-Origin: *

        Server: Werkzeug/0.9.6 Python/2.7.9

        Date: Sat, 31 Jan 2015 22:29:56 GMT

        <h1>Hello CORS!</h1> Read about my spec at the

        <a href="http://www.w3.org/TR/cors/">W3</a> Or, checkout my documentation

        on <a href="https://github.com/corydolphin/flask-cors">Github</a>

    '''

    return '''<h1>Hello CORS!</h1> Read about my spec at the

<a href="http://www.w3.org/TR/cors/">W3</a> Or, checkout my documentation

on <a href="https://github.com/corydolphin/flask-cors">Github</a>'''

@app.route("/api/v1/users/create", methods=['GET', 'POST'])

@cross_origin(allow_headers=['Content-Type'])

def cross_origin_json_post():

    '''

        This view has CORS enabled for all domains, and allows browsers

        to send the Content-Type header, allowing cross domain AJAX POST

        requests.

Browsers will first make a preflight request to verify that the resource

        allows cross-origin POSTs with a JSON Content-Type, which can be simulated

        as:

        $ curl --include -X OPTIONS http://127.0.0.1:5000/api/v1/users/create \

            --header Access-Control-Request-Method:POST \

            --header Access-Control-Request-Headers:Content-Type \

            --header Origin:www.examplesite.com

        >> HTTP/1.0 200 OK

        Content-Type: text/html; charset=utf-8

        Allow: POST, OPTIONS

        Access-Control-Allow-Origin: *

        Access-Control-Allow-Headers: Content-Type

        Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT

        Content-Length: 0

        Server: Werkzeug/0.9.6 Python/2.7.9

        Date: Sat, 31 Jan 2015 22:25:22 GMT

        $ curl --include -X POST http://127.0.0.1:5000/api/v1/users/create \

            --header Content-Type:application/json \

            --header Origin:www.examplesite.com

        >> HTTP/1.0 200 OK

        Content-Type: application/json

        Content-Length: 21

        Access-Control-Allow-Origin: *

        Server: Werkzeug/0.9.6 Python/2.7.9

        Date: Sat, 31 Jan 2015 22:25:04 GMT

        {

          "success": true

        }

    '''

    return jsonify(success=True)

if __name__ == "__main__":

    app.run(debug=True)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,029评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,238评论 3 388
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,576评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,214评论 1 287
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,324评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,392评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,416评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,196评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,631评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,919评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,090评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,767评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,410评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,090评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,328评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,952评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,979评论 2 351