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

相关推荐
cxr82812 小时前
GPU 加速声场求解器 CUDA Kernel 实现细节 —— 高频超声传播仿真并行计算引擎
人工智能·python·目标跟踪
枫叶林FYL13 小时前
第10章 符号推理与神经符号AI
pytorch·python·深度学习
nimadan1213 小时前
剧本杀app2025推荐,多类型剧本体验与社交互动优势
人工智能·python
HAPPY酷14 小时前
Python高阶开发:从底层原理到架构设计的进阶之路
开发语言·python
sxhcwgcy14 小时前
SpringBoot 使用 spring.profiles.active 来区分不同环境配置
spring boot·后端·spring
疯狂打码的少年14 小时前
【Day 6 Java转Python】字符串处理的“降维打击”
java·开发语言·python
2301_7644413314 小时前
家国同构模型:计算社会学的创新探索
python·数学建模
ShCDNay15 小时前
Python核心底层知识(个人记录)
开发语言·python
来自远方的老作者15 小时前
第7章 运算符-7.2 赋值运算符
开发语言·数据结构·python·赋值运算符
来自远方的老作者15 小时前
第7章 运算符-7.1 算术运算符
开发语言·数据结构·python·算法·算术运算符