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

相关推荐
love530love38 分钟前
【ComfyUI】解决 ModuleNotFoundError: No module named ‘inference_core_nodes‘ 问题
人工智能·windows·python·comfyui·inference-core
亚亚的学习和分享2 小时前
python基础语法----条件语句
python
山岚的运维笔记3 小时前
SQL Server笔记 -- 第73章:排序/对行进行排序
数据库·笔记·后端·sql·microsoft·sqlserver
苍何3 小时前
豆包还能这么玩?附 13 大隐藏玩法,效率起飞(建议收藏)
后端
苍何3 小时前
Kimi 版 OpenClaw 来了,5000+ Skills 随便用,确实给力!
后端
Zzz 小生3 小时前
LangChain Streaming-Overview:流式处理使用完全指南
人工智能·python·语言模型·langchain·github
yzx9910133 小时前
Python数据结构入门指南:从基础到实践
开发语言·数据结构·python
百锦再4 小时前
Jenkins 全面精通指南:从入门到脚本大师
运维·后端·python·servlet·django·flask·jenkins
FYKJ_20104 小时前
springboot大学校园论坛管理系统--附源码42669
java·javascript·spring boot·python·spark·django·php
forestsea4 小时前
优雅终结启动顺序噩梦:ObjectProvider —— Spring 4.3 开始引入
java·后端·spring