flask 实践

flask框架研究:

https://blog.csdn.net/shifengboy/article/details/114274271

https://blog.csdn.net/weixin_67531112/article/details/128256170

实现下载文件功能

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

相关推荐
喵手2 分钟前
Python爬虫实战:构建全球节假日数据库 - requests+lxml 实战时区节假日网站采集(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·构建全球节假日数据库·采集时区节假日数据·采集节假日sqlite存储
galaxyffang4 分钟前
A2A协议的简单应用
python·ai
一晌小贪欢6 分钟前
Python在物联网(IoT)中的应用:从边缘计算到云端数据处理
开发语言·人工智能·python·物联网·边缘计算
好家伙VCC9 分钟前
# 发散创新:基于Solidity的DeFi协议设计与实现——从原理到实战代码解析在区块链世界中,**DeFi(去中心化金
java·python·去中心化·区块链
墨染青竹梦悠然12 分钟前
基于SpringBoot + vue的农产品销售系统(华夏鲜仓)
vue.js·spring boot·python·django·毕业设计·毕设
维度攻城狮15 分钟前
Python控制系统仿真案例-RLC电路系统
python·线性代数·矩阵
zhangfeng113315 分钟前
GitHub博主hiyouga与LlamaFactory项目研究报告
python·大语言模型
消失的旧时光-194318 分钟前
第二十一课:系统是怎么一步步拆坏的?——单体到模块化实践(完整工程版)
java·spring boot·后端·架构
wanderful_18 分钟前
自定义用户体系下 Django 业务模块开发踩坑与通用解决方案(技术分享版)
后端·python·django
纯.Pure_Jin(g)20 分钟前
【Python练习五】Python 正则与网络爬虫实战:专项练习(2道经典练习带你巩固基础——看完包会)
开发语言·vscode·python