网络编程
位置:首页>> 网络编程>> Python编程>> python 详解如何写flask文件下载接口

python 详解如何写flask文件下载接口

作者:剑客阿良_ALiang  发布时间:2023-05-04 21:07:06 

标签:python,flask,文件,下载,接口

简述

写一个简单的flask文件下载接口。

依赖

flask、gevent

代码

不废话上代码。


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 23 19:53:18 2021
@author: huyi
"""

from flask import Flask, request, make_response, send_from_directory
from gevent.pywsgi import WSGIServer
from gevent import monkey

# 将python标准的io方法,都替换成gevent中的同名方法,遇到io阻塞gevent自动进行协程切换
monkey.patch_all()
app = Flask(__name__)

@app.route("/download", methods=['GET'])
def download_file():
   get_data = request.args.to_dict()
   file_path = get_data.get('fileName')

response = make_response(
       send_from_directory('/Users/huyi/Movies/Videos',file_path,as_attachment=True))
   response.headers["Content-Disposition"] = "attachment; filename={}".format(
       file_path.encode().decode('latin-1'))
   return response

if __name__ == '__main__':
   WSGIServer(('0.0.0.0', 8080), app).serve_forever()

准备数据:

python 详解如何写flask文件下载接口

浏览器输入:http://localhost:8080/download?fileName=test.mp4

python 详解如何写flask文件下载接口

下载完成。

来源:https://huyi-aliang.blog.csdn.net/article/details/120921334

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com