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

相关推荐
西安邮电大学3 小时前
2026华为OD机考真题附答案-准备生日礼物
java·后端
Trouvaille ~3 小时前
【Redis篇】Hash 哈希:字段级操作与对象存储的最佳实践
数据库·redis·后端·算法·缓存·哈希算法·键值对
辞忧九千七3 小时前
吃透Redis7核心数据结构:从基础用法到实战场景(Python版)
开发语言·数据结构·redis·python
空圆小生3 小时前
基于 Python+Vue3 的 AI 人脸识别门禁考勤系统
开发语言·人工智能·python
Yoshizawa-Violet3 小时前
模板方法模式实战:重构Agent工具审批,告别重复代码
python·agent·模板方法
Rust研习社3 小时前
Nightly 前瞻:cargo-script 让 Rust 也能写脚本
后端·rust·编程语言
AskHarries3 小时前
Chrome 插件有没有机会
后端
浩风祭月3 小时前
一次诡异的 MySQL 死锁,靠 AI 分析日志十分钟定位根因
后端·ai编程
HjhIron3 小时前
Python列表与LLM接口实战:从切片到DeepSeek调用
python
搬砖的小码农_Sky3 小时前
macOS Sequoia上如何安装Python开发环境?
开发语言·python·macos