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

相关推荐
高频因子挖掘机4 分钟前
盘中筛选要同时看价格和盘口?按需分层比“一次全拿”更好维护
后端·github·api
asong8 分钟前
从写代码到部署上线,Cloudflare 给 AI 配了一把新钥匙
前端·javascript·后端
言乐69 分钟前
Python基于关键词分拣快递(适用于电商与货运代理等)
开发语言·python·django·virtualenv·pygame
代码方舟10 分钟前
Python数据工程:利用天远名下车辆车牌查询A优化个人债务重组与清偿能力评估合规体验
人工智能·python
卷无止境10 分钟前
当AI写代码遇见Rust为什么会卡壳
后端·python
Percy_kk13 分钟前
Django的CRUD映射
后端·django
栈溢出了15 分钟前
LangGraph State、节点与动态路由学习笔记
python
用户EasyAdminBlazor15 分钟前
Blazor Server 性能优化实战:Circuit、数据库、Redis 与并发
后端
用户0190275816119 分钟前
A 股代码后缀 .SH/.SZ/.BJ 怎么区分?Python 怎么统一处理沪深京港美股代码?
python
王中阳Go19 分钟前
Agent 第一句就 500,我们查了三轮:入口日志少打了一个参数
后端·agent·ai编程