from flask import Blueprint, request, jsonify, send_from_directory from flask_login import login_required, current_user import sys import os # 添加父目录到路径 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from models import db, Resource bp = Blueprint('api', __name__) @bp.route('/download/', methods=['GET']) def download_resource(resource_id): """下载资源文件""" resource = Resource.query.get_or_404(resource_id) # 检查是否需要登录 if resource.is_protected and not current_user.is_authenticated: return jsonify({'error': 'Authentication required'}), 401 # 增加下载计数 resource.download_count += 1 db.session.commit() # 返回文件 uploads_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'uploads') filename = os.path.basename(resource.file_path) return send_from_directory(uploads_dir, filename, as_attachment=True) @bp.route('/stats', methods=['GET']) @login_required def get_stats(): """获取统计数据(需要登录)""" from models import Article, Resource, TeamMember stats = { 'articles': Article.query.count(), 'resources': Resource.query.count(), 'team_members': TeamMember.query.count(), 'total_downloads': db.session.query(db.func.sum(Resource.download_count)).scalar() or 0 } return jsonify({'stats': stats}), 200 @bp.route('/protected-content', methods=['GET']) @login_required def get_protected_content(): """获取受保护内容(需要登录)""" from models import Article, Resource protected_articles = Article.query.filter_by(is_protected=True, published=True).all() protected_resources = Resource.query.filter_by(is_protected=True).all() return jsonify({ 'articles': [article.to_dict() for article in protected_articles], 'resources': [resource.to_dict() for resource in protected_resources] }), 200