CORS(Cross-Origin Resource Sharing)是一种 W3C 规范,它定义了一种浏览器和服务器交互的方式来确定是否允许跨源请求。在 Python web 框架中,实现 CORS 通常涉及到在响应头中添加适当的字段,以便告诉浏览器允许哪些来源的请求。
以下是一些 Python web 框架中实现 CORS 的详解:
Flask
在 Flask 中,你可以使用 flask_cors
扩展来轻松实现 CORS。
首先,安装 flask_cors
:
bash复制代码
pip install flask-cors |
然后,在你的 Flask 应用中使用它:
python复制代码
from flask import Flask | |
from flask_cors import CORS | |
app = Flask(__name__) | |
CORS(app, resources={r"/api/*": {"origins": "*"}}) | |
@app.route('/api/data', methods=['GET']) | |
def get_data(): | |
return {'data': 'This is some data'} | |
if __name__ == '__main__': | |
app.run() |
在上面的例子中,resources
参数定义了哪些 URL 路径应该启用 CORS,以及哪些来源被允许。在这个例子中,所有来源(*
)都被允许访问 /api/*
路径。
FastAPI
在 FastAPI 中,CORS 支持是内置的,你无需安装额外的扩展。你可以通过 add_middleware
方法或直接在 FastAPI
应用实例上设置 CORS。
python复制代码
from fastapi import FastAPI, CORSMiddleware | |
app = FastAPI() | |
# 添加 CORS 中间件 | |
app.add_middleware( | |
CORSMiddleware, | |
allow_origins=["*"], | |
allow_credentials=True, | |
allow_methods=["*"], | |
allow_headers=["*"], | |
) | |
@app.get("/") | |
async def read_root(): | |
return {"Hello": "World"} | |
@app.get("/items/{item_id}") | |
async def read_item(item_id: int): | |
return {"item_id": item_id} |
在这个例子中,我们添加了一个 CORSMiddleware
中间件,并允许所有来源(*
)、所有方法(*
)和所有头部(*
)。allow_credentials
设置为 True
允许携带凭证的请求(如 cookies)。
Django
在 Django 中,CORS 可以通过安装 django-cors-headers
应用来实现。
首先,安装 django-cors-headers
:
bash复制代码
pip install django-cors-headers |
然后,在 Django 的 settings.py
文件中添加 corsheaders
到 INSTALLED_APPS
,并配置 CORS 设置:
python复制代码
INSTALLED_APPS = [ | |
# ... | |
'corsheaders', | |
# ... | |
] | |
MIDDLEWARE = [ | |
# ... | |
'corsheaders.middleware.CorsMiddleware', | |
# ... | |
] | |
CORS_ALLOW_ALL_ORIGINS = True | |
# 或者指定允许哪些源 | |
# CORS_ORIGIN_ALLOW_ALL = False | |
# CORS_ORIGIN_WHITELIST = ( | |
# 'http://example.com', | |
# 'http://www.example.com', | |
# ) |
在 Django 中配置 CORS 时,你可以全局允许所有来源,或者指定一个白名单。
总结
不同的 Python web 框架提供了不同的方式来处理 CORS。但无论使用哪个框架,实现 CORS 的核心都是添加适当的响应头来告诉浏览器哪些跨源请求是被允许的。在实际应用中,你应该仔细考虑哪些源应该被允许,并避免使用过于宽松的 CORS 配置,以维护应用的安全性。