Flask框架使用flask_cors解决跨域问题的方案
- 2018-11-07 01:20:18
- 开发
- 56
- shevechco
CORS是一种安全机制,用于控制不同域之间的资源访问。当前端应用想要访问与自己不同域(包括不同的协议、域名或端口)的API时,就需要使用CORS。
今天我们主要讲讲Flask框架进行跨域,也是比较简单的,几步就能搞定。
先安装flask_cors包
pip install flask_cors
然后我们包这个包导入到项目
from flask_cors import CORS
我们还是在应用工厂中初始化flask_cors
我们首先在扩展管理的文件中实例化CORS,我扩展统一注册在__init__.py文件
#!/usr/bin/python3
#coding:utf-8
__author__ = 'yang.su'
'''
Flask工厂函数待注册的所有扩展
'''
from flask_login import LoginManager
from flask_caching import Cache
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_cors import CORS
from peewee import Proxy
loginmanager = LoginManager()
cache = Cache()
limiter = Limiter(key_func=get_remote_address,storage_uri="memory://")
data_proxy = Proxy()
cors = CORS(supports_credentials=True)
然后可以使用init_app方法挂在道app应用中
def create_app():
......
cors.init_app(app)
......
在挂载cors实例的时候我们也是可以直接做全局的跨域配置
def create_app():
......
CORS(app, resources={
r"/blog_api/*": {
"origins": ["http://localhost:5173", "https://sulao.cn"], #允许的跨域源
"methods": ["GET", "POST", "PUT", "DELETE"],
"allow_headers": ["Content-Type", "Authorization", "X-Requested-With"], #允许的请求头
"expose_headers": ["Content-Range", "X-Total-Count"],
"supports_credentials": True, # 允许携带认证信息
"max_age": 600 #预检请求的有效期(秒)
}
})
......
上述是在应用工厂函数中配置,如果需要允许所有所有跨域的请求,直接改成如下配置
CORS(app, resources=r'/*')
当然我们也可以在视图函数中直接使用限制,使用方法如下:
#首页
@blog_api.route('/index', methods=['GET'])
@cross_origin(origin='*')
def index():
p = request.args.get("p", 1)
limit = request.args.get("limit", current_app.config["PAGE_SIZE"])
query = BPost.select().where(BPost.is_show == 1).order_by(BPost.id.desc())
data = paginated(query, int(p), int(limit))
return jsonify(data)
上述是允许所有的跨域请求来源,当然我们也可以指定跨域请求来源,写法如下:
@cross_origin(origins=['http://localhost:5173'])
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:http://www.sulao.cn/post/567