#!/usr/bin/env python # -*- coding: utf-8 -*- """ 图片库管理接口 """ from flask import Blueprint, request, jsonify import logging from datetime import datetime from auth_utils import require_auth, AuthUtils from database_config import get_db_manager from log_utils import log_create, log_update, log_delete, log_error, log_operation logger = logging.getLogger(__name__) # 创建蓝图 image_bp = Blueprint('image', __name__, url_prefix='/api/images') @image_bp.route('/list', methods=['GET']) @require_auth def get_images_list(): """获取图片列表""" try: current_user = AuthUtils.get_current_user() enterprise_id = current_user.get('enterprise_id') if not enterprise_id: return jsonify({ 'code': 400, 'message': '无法获取企业ID', 'data': None }), 400 # 获取查询参数 page = int(request.args.get('page', 1)) page_size = int(request.args.get('pageSize', 20)) keyword = request.args.get('keyword', '').strip() product_id = request.args.get('product_id', '').strip() image_type = request.args.get('type', '').strip() # 构建查询条件 where_conditions = ["1=1"] # ai_images表没有enterprise_id params = [] if keyword: where_conditions.append("(image_name LIKE %s OR keywords LIKE %s)") keyword_pattern = f"%{keyword}%" params.extend([keyword_pattern, keyword_pattern]) if product_id: # 跨表查询,通过ai_image_tags_relation关联 where_conditions.append("id IN (SELECT image_id FROM ai_image_tags_relation WHERE product_id = %s)") params.append(product_id) if image_type: where_conditions.append("image_type_name LIKE %s") params.append(f"%{image_type}%") where_clause = " AND ".join(where_conditions) # 计算偏移量 offset = (page - 1) * page_size db_manager = get_db_manager() # 查询总数 count_sql = f""" SELECT COUNT(*) as total FROM ai_images WHERE {where_clause} """ count_result = db_manager.execute_query(count_sql, params) total = count_result[0]['total'] # 查询图片列表 sql = f""" SELECT id, image_name, image_url, image_thumb_url, thumbnail_url, image_type_id, image_type_name, department, keywords, size_type, file_size, width, height, status, created_at, updated_at FROM ai_images WHERE {where_clause} ORDER BY created_at DESC LIMIT %s OFFSET %s """ params.extend([page_size, offset]) images = db_manager.execute_query(sql, params) logger.info(f"获取图片列表成功,总数: {total}") return jsonify({ 'code': 200, 'message': 'success', 'data': { 'total': total, 'list': images }, 'timestamp': int(datetime.now().timestamp() * 1000) }) except Exception as e: logger.error(f"[获取图片列表] 处理请求时发生错误: {str(e)}", exc_info=True) return jsonify({ 'code': 500, 'message': '服务器内部错误', 'data': None }), 500 @image_bp.route('/upload', methods=['POST']) @require_auth def upload_image(): """上传图片""" try: current_user = AuthUtils.get_current_user() enterprise_id = current_user.get('enterprise_id') if not enterprise_id: return jsonify({ 'code': 400, 'message': '无法获取企业ID', 'data': None }), 400 data = request.get_json() if not data: return jsonify({ 'code': 400, 'message': '请求参数错误', 'data': None }), 400 # 验证必需字段 required_fields = ['image_url', 'image_type_name'] for field in required_fields: if not data.get(field): return jsonify({ 'code': 400, 'message': f'缺少必需字段: {field}', 'data': None }), 400 db_manager = get_db_manager() # 插入图片记录 sql = """ INSERT INTO ai_images (image_name, image_url, image_thumb_url, thumbnail_url, image_type_id, image_type_name, department, keywords, size_type, upload_user_id, status) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ image_id = db_manager.execute_insert(sql, ( data.get('image_name', ''), data['image_url'], data.get('image_thumb_url', ''), data.get('thumbnail_url', ''), data.get('image_type_id', 0), data['image_type_name'], data.get('department', ''), data.get('keywords', ''), data.get('size_type', 'medical'), current_user.get('user_id', 0), 'active' )) logger.info(f"上传图片成功: ID {image_id}") return jsonify({ 'code': 200, 'message': '上传成功', 'data': {'id': image_id, 'url': data['image_url']}, 'timestamp': int(datetime.now().timestamp() * 1000) }) except Exception as e: logger.error(f"[上传图片] 处理请求时发生错误: {str(e)}", exc_info=True) return jsonify({ 'code': 500, 'message': '服务器内部错误', 'data': None }), 500 @image_bp.route('/batch-upload', methods=['POST']) @require_auth def batch_upload_images(): """批量上传图片""" try: current_user = AuthUtils.get_current_user() enterprise_id = current_user.get('enterprise_id') if not enterprise_id: return jsonify({ 'code': 400, 'message': '无法获取企业ID', 'data': None }), 400 data = request.get_json() if not data or not data.get('images'): return jsonify({ 'code': 400, 'message': '请求参数错误', 'data': None }), 400 db_manager = get_db_manager() uploaded_ids = [] for img in data['images']: # 验证必需字段 if not img.get('image_url') or not img.get('image_type_name'): continue # 插入图片记录 sql = """ INSERT INTO ai_images (image_name, image_url, image_thumb_url, thumbnail_url, image_type_id, image_type_name, department, keywords, size_type, upload_user_id, status) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ image_id = db_manager.execute_insert(sql, ( img.get('image_name', ''), img['image_url'], img.get('image_thumb_url', ''), img.get('thumbnail_url', ''), img.get('image_type_id', 0), img['image_type_name'], img.get('department', ''), img.get('keywords', ''), img.get('size_type', 'medical'), current_user.get('user_id', 0), 'active' )) uploaded_ids.append(image_id) logger.info(f"批量上传图片成功: {len(uploaded_ids)}张") return jsonify({ 'code': 200, 'message': '批量上传成功', 'data': { 'uploaded_count': len(uploaded_ids), 'ids': uploaded_ids }, 'timestamp': int(datetime.now().timestamp() * 1000) }) except Exception as e: logger.error(f"[批量上传图片] 处理请求时发生错误: {str(e)}", exc_info=True) return jsonify({ 'code': 500, 'message': '服务器内部错误', 'data': None }), 500 @image_bp.route('/', methods=['DELETE']) @require_auth def delete_image(image_id): """删除图片""" try: current_user = AuthUtils.get_current_user() enterprise_id = current_user.get('enterprise_id') if not enterprise_id: return jsonify({ 'code': 400, 'message': '无法获取企业ID', 'data': None }), 400 db_manager = get_db_manager() # 检查图片是否存在 check_sql = "SELECT id FROM ai_images WHERE id = %s" existing = db_manager.execute_query(check_sql, (image_id,)) if not existing: return jsonify({ 'code': 404, 'message': '图片不存在', 'data': None }), 404 # 删除图片记录(软删除) sql = "UPDATE ai_images SET status = 'deleted' WHERE id = %s" db_manager.execute_update(sql, (image_id,)) logger.info(f"删除图片成功: ID {image_id}") return jsonify({ 'code': 200, 'message': '删除成功', 'data': None, 'timestamp': int(datetime.now().timestamp() * 1000) }) except Exception as e: logger.error(f"[删除图片] 处理请求时发生错误: {str(e)}", exc_info=True) return jsonify({ 'code': 500, 'message': '服务器内部错误', 'data': None }), 500