图床项目实战:后续开发与优化

在之前的文章中,我们介绍了图床项目的基本实现,接下来,我将提供扩展功能和优化性能的关键代码片段。

一、图片分类管理

首先,我们需要在数据库中创建分类表,并在图片表中添加分类字段。
python 复制代码
class Category(db.Model):  
    id = db.Column(db.Integer, primary_key=True)  
    name = db.Column(db.String(50), nullable=False, unique=True)  
  
class Image(db.Model):  
    # ... 省略其他字段 ...  
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=False)  
    category = db.relationship("Category", back_populates="images")  
  
# 在Category模型中  
category.images = db.relationship("Image", order_by=Image.id, back_populates="category")

然后,我们添加创建和获取分类的接口。
python 复制代码
@app.route('/category', methods=['POST'])  
def create_category():  
    name = request.json.get('name')  
    if not name:  
        return jsonify({'error': 'Name is required'}), 400  
    category = Category(name=name)  
    db.session.add(category)  
    db.session.commit()  
    return jsonify({'id': category.id}), 201  
  
@app.route('/categories', methods=['GET'])  
def get_categories():  
    categories = Category.query.all()  
    return jsonify([{'id': category.id, 'name': category.name} for category in categories])

二、图片压缩

使用Pillow库进行图片压缩:
python 复制代码
from PIL import Image  
from io import BytesIO  
  
def compress_image(image_file):  
    image = Image.open(image_file)  
    output_io_stream = BytesIO()  
    image.save(output_io_stream, format='JPEG', quality=80)  
    output_io_stream.seek(0)  
    return output_io_stream  
  
# 在上传接口中使用  
@app.route('/upload', methods=['POST'])  
def upload_image():  
    # ... 省略其他代码 ...  
    file = request.files['file']  
    compressed_image = compress_image(file)  
    filename = file.filename  
    compressed_image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))  
    # ... 省略其他代码 ...

三、访问控制

为了简单起见,我们可以使用装饰器进行基本的访问控制。
python 复制代码
def login_required(func):  
    @wraps(func)  
    def wrapper(*args, **kwargs):  
        if 'user' not in session:  
            return redirect(url_for('login'))  
        return func(*args, **kwargs)  
    return wrapper  
  
@app.route('/admin/images', methods=['GET', 'DELETE'])  
@login_required  
def admin_images():  
    # ... 实现管理员对图片的查看和删除功能 ...

四、文件上传验证

在上传接口中,我们可以添加文件验证逻辑。
python 复制代码
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}  
  
def allowed_file(filename):  
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS  
  
@app.route('/upload', methods=['POST'])  
def upload_image():  
    if 'file' not in request.files:  
        return jsonify({'error': 'No file part'}), 400  
    file = request.files['file']  
    if file.filename == '':  
        return jsonify({'error': 'No selected file'}), 400  
    if not allowed_file(file.filename):  
        return jsonify({'error': 'Invalid file type'}), 400  
    # ... 省略其他代码 ...

  • 请注意,上述代码只是示例性的,并未包含完整的错误处理和安全措施。在实际开发中,你需要确保对上传的文件进行更全面的验证,并对用户输入进行适当的清理和转义,以防止潜在的安全漏洞。

此外,对于分布式存储和CDN加速等高级功能,通常需要使用专门的第三方服务和库来实现,这超出了简单示例的范围。

相关推荐
Sylvia33.3 小时前
LOL实时数据接入深度解析:从WebSocket到完整数据模型
java·网络·python·websocket·网络协议
梦想不只是梦与想3 小时前
Web 服务器网关协议:ASGI 和 WSGI
服务器·python·fastapi
ai小陈5 小时前
PyTorch DataLoader数据加载性能排查:GPU利用率低的实操指南
人工智能·pytorch·python·深度学习·ai·gpu算力
2601_962299248 小时前
Azure python操作系统列表
python·操作系统·azure·虚拟机·存储配置文件
2601_962071578 小时前
【Java报错已解决】org.springframework.beans.factory.BeanCreationException
java·开发语言
学术 学术 Fun9 小时前
如何用 API 与 Webhook 批量把图表图片转换成 VSDX
python·自动化·api·visio
淡海水9 小时前
07-04-并发-ConcurrentBag-T-工作窃取WorkStealing算法
开发语言·算法·c#·bag·concurrent·workstealing
2601_9621005410 小时前
python包和模块的内容整理
python·模块·导入·虚拟环境·
CS_Zero10 小时前
C语言sizeof是函数吗?
c语言·开发语言
二进制漫游记10 小时前
FastAPI项目集成 Qdrant向量数据库+阿里云Embedding完整实战(工具封装+业务调用)
数据库·python·阿里云·embedding