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

相关推荐
中科三方16 分钟前
域名NS记录修改全攻略:规则、误区、实操流程和常见问题
java·后端·spring
2401_8274999922 分钟前
python核心语法04-函数
开发语言·python
Full Stack Developme27 分钟前
SpringBoot配置文件优先级详解
java·spring boot·后端
MarkHD37 分钟前
从“能跑”到“好用”:Python脚本监控与告警实战(邮件/钉钉/企业微信)
python·钉钉·企业微信
yuhaiqiang40 分钟前
【珍藏干货】累计阅读破百万:我如何靠“标题公式”把冷门技术写出爆款的?
前端·后端·程序员
艾莉丝努力练剑44 分钟前
【Linux系统:多线程】线程概念与控制
linux·运维·服务器·c++·后端·学习·操作系统
徒 花1 小时前
Python知识学习03
开发语言·python·学习
喝醉的小喵1 小时前
iptables 规则重启机器后丢失导致k8s网络不可用
网络·后端·容器·kubernetes·虚拟化
人间打气筒(Ada)1 小时前
「码动四季·开源同行」go语言:如何处理 Go 错误异常与并发陷阱?
开发语言·后端·golang·defer·panic·errors·并发陷阱
wjcroom1 小时前
电子python模拟出的一个完美风暴
开发语言·python·数学建模·物理学