Flask 图片预览功能实现:使用 Blueprint 和 MethodView
要实现一个图片预览功能,可以使用以下代码:
from flask import send_from_directory
from flask_smorest import Blueprint
from flask.views import MethodView
import os
# 创建一个蓝图
bp = Blueprint('preview', 'preview', url_prefix='/preview', description='Image Preview')
# 创建一个视图类
class PreviewAPI(MethodView):
def get(self, filename):
# 获取指定目录下的所有图片文件
image_files = [f for f in os.listdir('path/to/images') if f.endswith(('.png', '.jpg', '.jpeg', '.gif'))]
# 如果指定的文件名存在于目录中,则返回该文件
if filename in image_files:
return send_from_directory('path/to/images', filename)
# 如果指定的文件名不存在,则返回错误信息
return {'message': 'File not found'}, 404
# 将视图类添加到蓝图中
bp.add_url_rule('/<string:filename>', view_func=PreviewAPI.as_view('image_preview'))
# 注册蓝图到Flask应用
app.register_blueprint(bp)
在上述代码中,需要将'path/to/images'替换为存储图片的实际目录路径。可以通过访问/preview/filename来预览指定目录下的图片文件。如果文件存在,则会返回该文件;如果文件不存在,则会返回错误信息。
原文地址: https://www.cveoy.top/t/topic/p0RJ 著作权归作者所有。请勿转载和采集!