flask 实践

flask框架研究:

https://blog.csdn.net/shifengboy/article/details/114274271

https://blog.csdn.net/weixin_67531112/article/details/128256170

实现下载文件功能

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

相关推荐
Metaphor6924 分钟前
使用 Python 加密或解密 Word 文档
python·安全·word
铭毅天下6 分钟前
当搜索引擎遇上 Rust——深度解读下一代实时搜索引擎 INFINI Pizza
开发语言·后端·搜索引擎·rust
用户298698530147 分钟前
Java 后端处理 Word 修订:批量接受与拒绝的自动化方案
java·后端
IT策士10 分钟前
Python 中间件系列:文件存储minio操作操
开发语言·python·中间件
马艳泽13 分钟前
win11环境查找jar包中字符串
后端
宁&沉沦19 分钟前
后端各框架热启动 极简启动命令(直接复制用)
后端
枕星而眠20 分钟前
Linux 共享内存与信号量全解析:原理、实践与避坑指南
linux·c语言·开发语言·后端·ubuntu
kree20 分钟前
Meilisearch:轻量搜索引擎的优雅选择,以及它在 RAG 中的应用
后端
Ulyanov21 分钟前
《从质点到位姿:基于Python与PyVista的导弹制导控制全栈仿真》: 驯服猛兽——自动驾驶仪(Autopilot)设计与舵机动力学
python·自动驾驶·雷达电子对抗
Ting-yu28 分钟前
SpringCloud快速入门(2)---- SpringCloud简介
后端·spring·spring cloud