flask 项目实践

实现下载文件功能

python 复制代码
vim test.py
import io
from flask import Flask, send_file

app = Flask(__name__)
@app.route('/download', methods=['GET'])
def download_file():
    # 当前目录下创建文件对象
    filename = "file.txt"
    file = open(filename, "w")

    # 写入数据到文件
    file.write("Hello, World!")

    # 关闭文件
    file.close()

    try:
        # 尝试打开文件并发送
        return send_file(filename, as_attachment=True)
    except PermissionError:
        return {"code": 403, "message":"文件权限错误,无法访问", "data":""}
    except Exception as e:
        return {"code": 500, "message":"发生错误", "data": str(e)}

if __name__ == '__main__':
    #app.run()
    svhost="0.0.0.0"
    svport=9001
    app.run(debug=True, host=svhost, port=svport)

1.filename 变量中提供要下载的文件的路径。

2.当访问 download 路由时,会触发download_file 函数,该函数使用send_file 方法将文件发送到客户端以进行下载

3.as_attachment=True 表示将文件作为附件下载,而不是在浏览器中直接打开。

powershell 复制代码
(base) user@ubuntu:~$ python test.py
 * Serving Flask app 'flash_send'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:9001
 * Running on http://192.168.98.169:9001
Press CTRL+C to quit
 * Restarting with watchdog (inotify)
 * Debugger is active!
 * Debugger PIN: 188-315-851

浏览器中输入 http://192.168.98.169:9001/download

相关推荐
Joy T12 小时前
Spring AI 2.0 Agent 进阶:Memory、State 与 Context Engineering 常见技术全景
java·人工智能·后端·spring·agent入门·agent state
西柚研究生12345612 小时前
论文分析17:YOLOv11_UAVNet:无人机航拍图像专用目标检测算法
人工智能·python·深度学习·算法·目标检测
沧海一笑-dj13 小时前
【Python】Python学习笔记-初识 Python
python·python安装·python解释器
打工仔折腾 AI13 小时前
FastAPI 从本机到生产服务器:Nginx+Gunicorn+Uvicorn 完整部署实录
人工智能·后端·python·nginx·fastapi·gunicorn
IT_陈寒13 小时前
Java空指针这次真把我坑惨了
前端·人工智能·后端
hanchenxing13 小时前
AI 数据管道重构:从函数堆到链式管道的可读性实践
python
hhzz13 小时前
【OpenCV 入门到精通 10】视频分析与光流跟踪:背景减除与运动检测
人工智能·python·opencv·性能优化
蓝胖的四次元口袋13 小时前
Python基础语法入门
python
Patrick在香港14 小时前
Python 抓 0.91 GB 香港法例:Agent 的进度该写进磁盘,不是写进上下文
爬虫·python·api·claude·香港