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

相关推荐
秦时明月之君临天下20 小时前
Python递归获取目录大小
python
三万棵雪松20 小时前
【AI小智后端部分(一)】
人工智能·python·ai小智
laplace012320 小时前
Part 3:模型调用、记忆管理与工具调用流程(LangChain 1.0)笔记(Markdown)
开发语言·人工智能·笔记·python·langchain·prompt
寒水馨20 小时前
com.github.oshi : oshi-core 中文文档(中英对照·API·接口·操作手册·全版本)以6.4.0为例,含Maven依赖、jar包、源码
java·后端
winfredzhang20 小时前
深度解析:利用 Python + Playwright 攻克动态网页 PPT 导出难题
python·powerpoint·截图·自动翻页
踏浪无痕20 小时前
CommitLog顺序写 —— 为什么RoceketMQ所有消息都往一个文件追加?
后端·面试·rocketmq
武子康20 小时前
大数据-200 决策树信息增益详解:信息熵、ID3 选特征与 Python 最佳切分实现
大数据·后端·机器学习
风送雨21 小时前
八周Python强化计划(七)
开发语言·python
ππ很开心66621 小时前
DAY 32 函数专题2:装饰器
开发语言·python