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

相关推荐
郑洁文10 小时前
基于Python的Web命令执行漏洞自动化检测系统
前端·python·网络安全·自动化
yingjie11011 小时前
Scanpy vs Seurat 深度对比:Python 与 R 的单细胞分析框架谁更强?
开发语言·python·r语言·生物信息学·单细胞转录组·seurat·scanpy
IT_陈寒11 小时前
Python的线程池居然把我坑在了垃圾回收这块
前端·人工智能·后端
包子BI大数据11 小时前
3.openclaw小龙虾简单版安装教程
人工智能·python·ai
程序大视界11 小时前
【Python系列课程】Pandas(四):数据统计与排序——describe、sort_values、sample
开发语言·python·pandas
zhangxingchao12 小时前
AI应用开发八:RAG相关技术总结
前端·人工智能·后端
吴佳浩12 小时前
Go史上最大“打脸”现场来了:泛型方法终于实现了
后端·go
Cthy_hy12 小时前
Python算法竞赛:排列组合核心用法
开发语言·python·算法
Huyuejia12 小时前
runtime-ask
后端
Rust研习社12 小时前
90% 的 Rust 新手都不知道的 3 个实用开发技巧
后端·rust·编程语言