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

相关推荐
海琴烟Sunshine6 分钟前
leetcode 338. 比特位计数 python
python·算法·leetcode
bcbnb43 分钟前
iOS 文件管理全攻略,多工具协同实现高效调试、数据导出与应用分析
后端
呆萌很44 分钟前
字典推导式练习题
python
tung tung tung sahur1 小时前
领略 Rust 抽象之美:自定义迭代器实现全解析
开发语言·后端·rust
用户3074596982071 小时前
容器(Container)—— 对象的“智能工厂+调度官”
后端·thinkphp
闲人编程1 小时前
Python在云计算中的应用:AWS Lambda函数实战
服务器·python·云计算·aws·lambda·毕设·codecapsule
程序猿小蒜1 小时前
基于springboot的校园社团信息管理系统开发与设计
java·前端·spring boot·后端·spring
申阳1 小时前
Day 4:02. 基于Nuxt开发博客项目-整合 Inspira UI
前端·后端·程序员
Mos_x1 小时前
28.<Spring博客系统⑤(部署的整个过程
java·后端
爱淋雨的鼬先生1 小时前
SpringBoot 概述
java·spring boot·后端