Flask 下载接口:使用 MethodView 和 Flask-Smorest 删除文件
使用from flask.views import MethodView from flask_smorest import Blueprint 写一个下载接口,将项目路径下的的图片下载下来,当图片被下载下来后,就删除原有目录下的图片内容:以下是一个使用Flask和Flask-Smorest编写的示例代码,用于创建一个下载接口并在下载完成后删除原始图片文件:
import os
from flask import Flask, send_file
from flask.views import MethodView
from flask_smorest import Blueprint
app = Flask(__name__)
api = Blueprint('api', 'api', url_prefix='/api')
@api.route('/download/<filename>', methods=['GET'])
class DownloadImage(MethodView):
def get(self, filename):
# 检查文件是否存在
if not os.path.exists(filename):
return {'message': 'File not found'}, 404
# 设置下载响应头
mimetype = 'application/octet-stream'
response_headers = {
'Content-Disposition': f'attachment; filename={filename}',
'Content-Type': mimetype
}
# 发送文件并删除原始文件
try:
return send_file(filename, as_attachment=True, attachment_filename=filename, mimetype=mimetype,
response_headers=response_headers)
finally:
os.remove(filename)
app.register_blueprint(api)
if __name__ == '__main__':
app.run(debug=True)
在此示例中,我们使用Flask创建一个应用程序,并使用Flask-Smorest创建一个蓝图。然后,我们使用MethodView创建一个类视图,处理GET请求以下载文件。在GET方法中,我们首先检查文件是否存在。如果文件不存在,我们返回一个404错误响应。如果文件存在,我们设置下载响应头并使用send_file函数发送文件。在finally块中,我们使用os.remove函数删除原始文件。
请注意,此代码仅供参考,并且假定文件位于运行该代码的项目路径下。您可能需要根据您的实际需求进行修改。
原文地址: https://www.cveoy.top/t/topic/pWJV 著作权归作者所有。请勿转载和采集!