怎样为Flask服务器配置跨域资源共享

为了在 Flask 服务器中配置跨域资源共享(CORS),你可以使用 flask-cors 扩展。这个扩展可以帮助你轻松地设置 CORS 规则,从而允许你的 Flask 服务器处理来自不同源的请求。

以下是配置 CORS 的步骤:

安装 flask-cors

首先,你需要安装 flask-cors 扩展。如果尚未安装,可以使用以下命令进行安装:

bash 复制代码
pip install flask-cors

配置 CORS

安装完成后,你可以在 Flask 应用中配置 CORS。以下是一个简单的示例:

python 复制代码
from flask import Flask, request, jsonify, Response
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 这将为所有路由启用CORS

@app.route('/api/stream-chat', methods=['POST'])
def stream_chat():
    if request.is_json:
        data = request.get_json()
        prompt = data.get('prompt')
        if prompt is None:
            return jsonify({"error": "Missing 'prompt' field"}), 400

        history = data.get('history')
        if history is None:
            return jsonify({"error": "Missing 'history' field"}), 400

        if not isinstance(history, list):
            return jsonify({"error": "'history' field must be a list"}), 400

        response = Response(generate(message=prompt, chat_history=history), mimetype='application/json')
        response.headers['Content-Type'] = 'text/event-stream'
        response.headers['Cache-Control'] = 'no-cache'
        response.headers['Connection'] = 'keep-alive'
        return response
    else:
        return jsonify({"error": "Request body must be JSON"}), 400

def generate(message, chat_history):
    import json
    import time
    while True:
        data = {
            "prompt": message,
            "history": chat_history,
            "response": "Generated response based on input"
        }
        yield f"data:{json.dumps(data)}\n\n"
        time.sleep(1)

if __name__ == '__main__':
    app.run(debug=True, threaded=True)

细粒度控制 CORS

如果你需要对 CORS 进行更细粒度的控制,比如只允许特定的域访问特定的路由,可以在 CORS 初始化时配置参数,或者使用装饰器。

允许特定域名
python 复制代码
CORS(app, resources={r"/api/*": {"origins": "http://example.com"}})
使用装饰器
python 复制代码
from flask_cors import cross_origin

@app.route('/api/stream-chat', methods=['POST'])
@cross_origin(origin='http://example.com')  # 仅允许来自 http://example.com 的请求
def stream_chat():
    # 你的处理逻辑

小结

通过配置 CORS,你可以允许来自不同源的请求访问你的 Flask 服务器。flask-cors 扩展提供了简便的方法来实现这一点,无论是全局配置还是针对特定路由的配置,都可以轻松实现。

相关推荐
孟健7 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞9 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽11 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程16 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪16 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook16 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python