Python | Flask 解决跨域问题
Python | Flask 解决跨域问题
系列文章目录
前言
我靠,又跨域了
使用步骤
1. 引入库
pip install flask-cors
2. 配置
flask-cors 有两种用法,一种为全局使用,一种对指定的路由使用
1. 使用 CORS函数 配置全局路由
from flask import Flask, request
from 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 expression and (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,
and the values must be a dictionary of kwargs, identical to the kwargs
of this function.
If the argument is a list, it is expected to be a list of regular
expressions, for which the app-wide configured options are applied.
If the argument is a string, it is expected to be a regular expression
for which the app-wide configured options are applied.
Default : Match all and apply app-level configuration
:type resources: dict, iterable or string
:param origins:
The origin, or list of origins to allow requests from.
The origin(s) may be regular expressions, case-sensitive strings,
or else an asterisk
Default : '*'
:type origins: list, string or regex
:param methods:
The method or list of methods which the allowed origins are allowed to
access for non-simple requests.
Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]
:type methods: list or string
:param expose_headers:
The header or list which are safe to expose to the API of a CORS API
specification.
Default : None
:type expose_headers: list or string
:param allow_headers:
The header or list 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, or else an asterisk.
Default : '*', allow all headers
:type allow_headers: list, string or regex
:param supports_credentials:
Allows users to make authenticated requests. If true, injects the
`Access-Control-Allow-Credentials` header in responses. This allows
cookies and credentials 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 time for which this CORS request maybe cached. This value
is set as the `Access-Control-Max-Age` header.
Default : None
:type max_age: timedelta, integer, string or None
:param send_wildcard: If True, and the 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 returned as per 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 an Origin than '*' is returned) informs CDNs and other
caches that the CORS headers are dynamic, and cannot be cached.
If False, the Vary header will never be injected or altered.
Default : True
:type vary_header: bool
2. 使用 @cross_origin 来配置单行路由
from flask import Flask, request
from flask_cors import cross_origin
app = Flask(__name__)
@app.route('/')
@cross_origin(supports_credentials=True)
def hello():
name = request.args.get("name", "World")
return f'Hello, {name}!'
其中 cross_origin 和 CORS 提供一些基本相同的参数。
常用的我们可以配置 origins、methods、allow_headers、supports_credentials
所有的配置项如下:
:param origins:
The origin, or list of origins to allow requests from.
The origin(s) may be regular expressions, case-sensitive strings,
or else an asterisk
Default : '*'
:type origins: list, string or regex
:param methods:
The method or list of methods which the allowed origins are allowed to
access for non-simple requests.
Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]
:type methods: list or string
:param expose_headers:
The header or list which are safe to expose to the API of a CORS API
specification.
Default : None
:type expose_headers: list or string
:param allow_headers:
The header or list 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, or else an asterisk.
Default : '*', allow all headers
:type allow_headers: list, string or regex
:param supports_credentials:
Allows users to make authenticated requests. If true, injects the
`Access-Control-Allow-Credentials` header in responses. This allows
cookies and credentials 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 time for which this CORS request maybe cached. This value
is set as the `Access-Control-Max-Age` header.
Default : None
:type max_age: timedelta, integer, string or None
:param send_wildcard: If True, and the 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 returned as per 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 an Origin than '*' is returned) informs CDNs and other
caches that the CORS headers are dynamic, and cannot be cached.
If False, the Vary header will never be injected or altered.
Default : True
:type vary_header: bool
:param automatic_options:
Only applies to the `cross_origin` decorator. If True, Flask-CORS will
override Flask's default OPTIONS handling to return CORS headers for
OPTIONS requests.
Default : True
:type automatic_options: bool
配置参数说明
| 参数 | 类型 | Head | 默认 | 说明 |
|---|---|---|---|---|
| resources | 字典、迭代器或字符串 | 无 | 全部 | 配置允许跨域的路由接口 |
| origins | 列表、字符串或正则表达式 | Access-Control-Allow-Origin | * | 配置允许跨域访问的源 |
| methods | 列表、字符串 | Access-Control-Allow-Methods | [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE] | 配置跨域支持的请求方式 |
| expose_headers | 列表、字符串 | Access-Control-Expose-Headers | None | 自定义请求响应的Head信息 |
| allow_headers | 列表、字符串或正则表达式 | Access-Control-Request-Headers | * | 配置允许跨域的请求头 |
| supports_credentials | 布尔值 | Access-Control-Allow-Credentials | False | 是否允许请求发送cookie |
| max_age | timedelta、整数、字符串 | Access-Control-Max-Age | None | 预检请求的有效时长 |
总结
在 flask 的跨域配置中,我们可以使用 flask-cors 来进行配置,其中 CORS 函数 用来做全局的配置, @cross_origin 来实现特定路由的配置
参考

Python | Flask 解决跨域问题的更多相关文章
- Flask解决跨域
Flask解决跨域 问题:网页上(client)有一个ajax请求,Flask sever是直接返回 jsonify. 然后ajax就报错:No 'Access-Control-Allow-Origi ...
- Python django解决跨域请求的问题
解决方案 1.安装django-cors-headers pip3 install django-cors-headers 2.配置settings.py文件 INSTALLED_APPS = [ . ...
- Flask允许跨域
什么是跨域 在 HTML 中,<a>, <form>, <img>, <script>, <iframe>, <link> 等标 ...
- Python之Flask和Django框架解决跨域问题,配合附加ajax和fetch等js代码
Flask框架py解决跨域问题示例: # -*- coding: utf- -*- # by zhenghai.zhang from flask import Flask, render_templa ...
- 使用nginx解决跨域问题(flask为例)
背景 我们单位的架构是在api和js之间架构一个中间层(python编写),以实现后端渲染,登录状态判定,跨域转发api等功能.但是这样一个中间会使前端工程师的工作量乘上两倍,原本js可以直接ajax ...
- element-ui + vue + node.js 与 服务器 Python 应用的跨域问题
跨越问题解决的两种办法: 1. 在 config => index.js 中配置 proxyTable 代理: proxyTable: { '/charts': { target: 'http: ...
- 前端通过Nginx反向代理解决跨域问题
在前面写的一篇文章SpringMVC 跨域,我们探讨了什么是跨域问题以及SpringMVC怎么解决跨域问题,解决方式主要有如下三种方式: JSONP CORS WebSocket 可是这几种方式都是基 ...
- 前后端分离djangorestframework——解决跨域请求
跨域 什么是跨域 比如一个链接:http://www.baidu.com(端口默认是80端口), 如果再来一个链接是这样:http://api.baidu.com,这个就算是跨域了(因为域名不同) 再 ...
- 在django中解决跨域AJAX
由于浏览器存在同源策略机制,同源策略阻止从一个源加载的文档或脚本获取另一个源加载的文档的属性. 特别的:由于同源策略是浏览器的限制,所以请求的发送和响应是可以进行,只不过浏览器不接收罢了. 浏览器同源 ...
- 【Nginx】使用Nginx如何解决跨域问题?看完这篇原来很简单!!
写在前面 当今互联网行业,大部分Web项目基本都是采用的前后端分离模式.前端为H5项目,后端为Java.PHP.Python等项目.而且大部分后端服务并不会只部署一套服务,而是会采用Nginx对后端服 ...
随机推荐
- C#9中使用静态匿名函数
匿名函数是很早以前在C#编程语言中引入的.尽管匿名功能有很多好处,但它们并不便宜.避免不必要的分配很重要,这就是为什么在C#9中引入静态匿名函数的原因.在C#9中,lambda或匿名方法可以具有静态修 ...
- Intel酷睿Ultra隆重登场:28W能效逆天!AI性能领先竞品5.4倍
作为Intel 1971年首款微处理器4004诞生以来变革幅度最大的产品,代号Meteor Lake的第一代酷睿Ultra今天终于正式发布了!相关笔记本.迷你机产品也会陆续发布上市. 有关于酷睿Ult ...
- Web 3.0 - 圈里的百科
Web3.0只是由业内人员制造出来的概念词语,最常见的解释是,网站内的信息可以直接和其他网站相关信息进行交互,能通过第三方信息平台同时对多家网站的信息进行整合使用:用户在互联网上拥有自己的数据,并能在 ...
- playwright 一些方法解决cloudflare防护页的问题
在尝试从一个使用Cloudflare Web应用程序防火墙(WAF)保护的网站获取数据时,我遇到了一些挑战.该网站的安全措施非常严格,以至于在正常浏览几个页面后,Cloudflare的检查页面就会出现 ...
- Apache Hudi 设计与架构解读
1. 简介 Apache Hudi(简称:Hudi)允许您在现有的hadoop兼容存储之上存储大量数据,同时提供两种原语,使得除了经典的批处理之外,还可以在数据湖上进行流处理. 这两种原语分别是: 1 ...
- [Ngbatis源码学习][SpringBoot] 由BeanFactoryPostProcessor想到
由BeanFactoryPostProcessor想到 在看Ngbatis源码时看到了对BeanFactoryPostProcessor后置处理器的使用,对其的使用并不是很了解,在此做一些学习和总结. ...
- BeginCTF 2024(自由赛道)MISC
real check in 题目: 从catf1y的笔记本中发现了这个神秘的代码 MJSWO2LOPNLUKTCDJ5GWKX3UN5PUEM2HNFXEGVCGL4ZDAMRUL5EDAUDFL5M ...
- EGF:指数型生成函数
对于一个数列 \(<a_n>\),定义其指数型生成函数(EGF)\(\hat{a}(x)=\displaystyle\sum_{n\ge 0}\dfrac{a_n}{n!}x^n\). 例 ...
- JS leetcode 宝石与石头 题解分析,正则字符组也有妙用
壹 ❀ 引 简单问题简单做,今天的题目来自leetcode771. 宝石与石头,字符串相关的一道题,题目描述如下: 给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头. S 中每个字符代 ...
- NC20313 [SDOI2008]仪仗队
题目链接 题目 题目描述 作为体育委员,C君负责这次运动会仪仗队的训练. 仪仗队是由学生组成的N * N的方阵,为了保证队伍在行进中整齐划一,C君会跟在仪仗队的左后方,根据其视线所及的学生人数来判断队 ...