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

相关推荐
DES 仿真实践家2 分钟前
【Day 11-N22】Python类(3)——Python的继承性、多继承、方法重写
开发语言·笔记·python
程序员张31 小时前
SpringBoot计时一次请求耗时
java·spring boot·后端
云泽野5 小时前
【Java|集合类】list遍历的6种方式
java·python·list
IMPYLH6 小时前
Python 的内置函数 reversed
笔记·python
程序员岳焱7 小时前
Java 与 MySQL 性能优化:Java 实现百万数据分批次插入的最佳实践
后端·mysql·性能优化
麦兜*8 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
大只鹅8 小时前
解决 Spring Boot 对 Elasticsearch 字段没有小驼峰映射的问题
spring boot·后端·elasticsearch
ai小鬼头8 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github
小赖同学啊8 小时前
物联网数据安全区块链服务
开发语言·python·区块链
码荼8 小时前
学习开发之hashmap
java·python·学习·哈希算法·个人开发·小白学开发·不花钱不花时间crud