Python Flask大刀解决跨域问题


本文摘自php中文网,作者coldplay.xixi,侵删。

python视频教程栏目为大家介绍Python Flask解决跨域问题。

系列文章目录

Table of Contents

  • 系列文章目录
  • 前言
  • 使用步骤
    • 1. 引入库
    • 2. 配置
      • 1. 使用CORS函数配置全局路由
      • 2. 使用@cross_origin来配置单行路由
    • 配置参数说明
  • 总结
  • 参考

前言

我靠,又跨域了

使用步骤

1. 引入库

pip install flask-cors复制代码

2. 配置

flask-cors 有两种用法,一种为全局使用,一种对指定的路由使用

1. 使用CORS函数配置全局路由

from flask import Flask, requestfrom flask_cors import CORS

 

app = Flask(__name__)

CORS(app, supports_credentials=True)复制代码

其中CORS提供了一些参数帮助我们定制一下操作。

常用的我们可以配置origins、methods、allow_headers、supports_credentials

所有的配置项如下:

:param resources:

    The series of regular expressionand(optionally) associated CORS

    options to be applied to the given resource path.

 

    If the argument is a dictionary, it's keys must be regular expressions,

    andthe values must be a dictionary of kwargs, identical to the kwargs

    of thisfunction.

 

    If the argument is a list, it is expected to be a list of regular

    expressions,forwhich the app-wide configured options are applied.

 

    If the argument is a string, it is expected to be a regular expression

    forwhich the app-wide configured options are applied.

 

    Default : Match allandapply app-level configuration

 

:type resources: dict, iterableorstring

 

:param origins:

    The origin,orlist of origins to allow requests from.

    The origin(s) may be regular expressions,case-sensitive strings,

    orelsean asterisk

 

    Default :'*'

:type origins: list, stringorregex

 

:param methods:

    The methodorlist of methods which the allowed origins are allowed to

    accessfornon-simple requests.

 

    Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH,DELETE]

:type methods: listorstring

 

:param expose_headers:

    The headerorlist which are safe to expose to the API of a CORS API

    specification.

 

    Default : None

:type expose_headers: listorstring

 

:param allow_headers:

    The headerorlist of header field names which can be used when this

    resource is accessed by allowed origins. The header(s) may be regular

    expressions,case-sensitive strings,orelsean asterisk.

 

    Default :'*', allow all headers

:type allow_headers: list, stringorregex

 

:param supports_credentials:

    Allows users to make authenticated requests. If true, injects the

    `Access-Control-Allow-Credentials` header in responses. This allows

    cookiesandcredentials to be submitted across domains.

 

    :note: This option cannot be used in conjuction with a'*'origin

 

    Default : False

:type supports_credentials: bool

 

:param max_age:

    The maximum timeforwhich this CORS request maybe cached. This value

    is setasthe `Access-Control-Max-Age` header.

 

    Default : None

:type max_age: timedelta, integer, stringorNone

 

:param send_wildcard: If True,andthe origins parameter is `*`, a wildcard

    `Access-Control-Allow-Origin` header is sent, rather than the

    request's `Origin` header.

 

    Default : False

:type send_wildcard: bool

 

:param vary_header:

    If True, the header Vary: Origin will be returnedasper the W3

    implementation guidelines.

 

    Setting this header when the `Access-Control-Allow-Origin` is

    dynamically generated (e.g. when there is more than one allowed

    origin,andan Origin than'*'is returned) informs CDNsandother

    caches that the CORS headers are dynamic,andcannot be cached.

 

    If False, the Vary header will never be injectedoraltered.

 

    Default : True

:type vary_header: bool复制代码

2. 使用@cross_origin来配置单行路由

from flask import Flask, requestfrom flask_cors import cross_origin

 

app = Flask(__name__)@app.route('/')@cross_origin(supports_credentials=True)def hello():

    name = request.args.get("name","World")   returnf'Hello, {name}!'复制代码

其中cross_origin和CORS提供一些基本相同的参数。

常用的我们可以配置origins、methods、allow_headers、supports_credentials

所有的配置项如下:

:param origins:

    The origin,orlist of origins to allow requests from.

    The origin(s) may be regular expressions,case-sensitive strings,

    orelsean asterisk

 

    Default :'*'

:type origins: list, stringorregex

 

:param methods:

    The methodorlist of methods which the allowed origins are allowed to

    accessfornon-simple requests.

 

    Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH,DELETE]

:type methods: listorstring

 

:param expose_headers:

    The headerorlist which are safe to expose to the API of a CORS API

    specification.

 

    Default : None

:type expose_headers: listorstring

 

:param allow_headers:

    The headerorlist of header field names which can be used when this

    resource is accessed by allowed origins. The header(s) may be regular

    expressions,case-sensitive strings,orelsean asterisk.

 

    Default :'*', allow all headers

:type allow_headers: list, stringorregex

 

:param supports_credentials:

    Allows users to make authenticated requests. If true, injects the

    `Access-Control-Allow-Credentials` header in responses. This allows

    cookiesandcredentials to be submitted across domains.

 

    :note: This option cannot be used in conjuction with a'*'origin

 

    Default : False

:type supports_credentials: bool

 

:param max_age:

    The maximum timeforwhich this CORS request maybe cached. This value

    is setasthe `Access-Control-Max-Age` header.

 

    Default : None

:type max_age: timedelta, integer, stringorNone

 

:param send_wildcard: If True,andthe origins parameter is `*`, a wildcard

    `Access-Control-Allow-Origin` header is sent, rather than the

    request's `Origin` header.

 

    Default : False

:type send_wildcard: bool

 

:param vary_header:

    If True, the header Vary: Origin will be returnedasper the W3

    implementation guidelines.

 

    Setting this header when the `Access-Control-Allow-Origin` is

    dynamically generated (e.g. when there is more than one allowed

    origin,and

相关阅读 >>

Python学习笔记之open()函数打开文件路径报错问题

Python是什么语言编写出来的

Python中numpy是什么

Python中关于os标准库的使用方法总结

Python注释是什么意思

如何用Python统计不同字符个数

Python pygame如何安装?详解Python pygame安装的教程实例

Python能做脚本吗

Python将dataframe的某一列作为index的方法

Python装饰器的深入浅出

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...