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

相关推荐
木泽八1 分钟前
python实现pdf拆分与合并
服务器·python·pdf
拾贰_C2 分钟前
[Python | pytorch | torchvision ] models like ResNet... 命名变量说明
开发语言·pytorch·python
清水白石00812 分钟前
《Python 装饰器模式与代理模式深度剖析:从语法技巧到架构实战》
python·代理模式·装饰器模式
dagouaofei12 分钟前
AI自动生成PPT工具横评,真实使用感受分享
人工智能·python·powerpoint
追逐时光者14 分钟前
精选 8 个 .NET 开发实用的类库,效率提升利器!
后端·.net
阿华田51237 分钟前
如何基于Jupyter内核自研NoteBook
ide·python·jupyter·自研notebook
a程序小傲39 分钟前
京东Java面试被问:Fork/Join框架的使用场景
java·开发语言·后端·postgresql·面试·职场和发展
想用offer打牌43 分钟前
面试官问Redis主从延迟导致脏数据读怎么解决?
redis·后端·面试
W如Q扬1 小时前
python程序使用supervisor启停
python·supervisor
Piar1231sdafa1 小时前
蓝莓果实检测与识别——基于decoupled-solo_r50_fpn_1x_coco模型实现
python