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

相关推荐
闲猫18 分钟前
LangChain / Core components / Models
开发语言·python·langchain
神奇小汤圆1 小时前
SpringBoot 相关的 Skills 全景指南
后端
神奇小汤圆1 小时前
高性能进程内队列 BufferQueue 1.0 版本发布
后端
爸爸6191 小时前
空数据状态与引导:多维度 UI 提示设计
后端
Reart2 小时前
Leetcode 674.最长连续递增序列 (719)
后端·算法
芒鸽2 小时前
HarmonyOS ArkUI Search 搜索框:联想词、历史记录与热门标签
后端
Reart3 小时前
Leetcode 714.买卖股票的最佳时机含手续费(719)
后端·算法
cui_ruicheng3 小时前
Python从入门到实战(十三):模块、包与环境管理
开发语言·python
芒鸽3 小时前
HarmonyOS ArkUI RichEditor 富文本编辑器:内联样式、Span 管理与格式工具栏
后端
花开彼岸天~3 小时前
Router 路由管理:pushUrl、replaceUrl、back 与参数传递
后端