kbzhishiku

This commit is contained in:
runny committed 2026-05-12 08:16:42 +08:00
1 parent 7f542f54a5
commit 08a19ebe96
68 files changed
+16602 -229

No files matched your search

+37 -16
View File
@@ -4,14 +4,25 @@ backend/app/api/agents.py
引用文件:flask, models, decorators
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
"""
from flask import Blueprint, jsonify, g
from app.models import Agent, User
from flask import Blueprint, jsonify
from app import db
from app.decorators import _get_current_user # 内部工具函数
from app.models import Agent, User
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
agents_bp = Blueprint('agents', __name__)
def _serialize_agent_row(row) -> dict:
return {
'id': row.id,
'name': row.name,
'description': row.description,
'icon_url': row.icon_url,
}
@agents_bp.route('', methods=['GET'])
def list_user_agents():
"""
@@ -23,12 +34,27 @@ def list_user_agents():
# 管理员:返回所有激活的 Agent
if user.role == 'admin':
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
agent_rows = (
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url)
.filter(Agent.is_active.is_(True))
.order_by(Agent.id.asc())
.all()
)
else:
# 普通用户:仅返回多对多关系中已授权的 Agent
agents = [a for a in user.agents if a.is_active]
agent_rows = [
type('AgentRow', (), {
'id': a.id,
'name': a.name,
'description': a.description,
'icon_url': a.icon_url,
})()
for a in user.agents
if a.is_active
]
# 序列化为前端所需字段
return jsonify([_serialize_agent_row(row) for row in agent_rows])
@agents_bp.route('/public', methods=['GET'])
def list_public_agents():
@@ -37,17 +63,12 @@ def list_public_agents():
用途:登录页面展示
"""
# 返回所有激活的 Agent,包含基本信息
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
data = [
{
'id': a.id,
'name': a.name,
'description': a.description,
'icon_url': a.icon_url,
}
for a in agents
]
return jsonify(data)
agent_rows = (
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url)
.filter(Agent.is_active.is_(True))
.order_by(Agent.id.asc())
.all()
)
return jsonify([_serialize_agent_row(row) for row in agent_rows])
+3 -3
View File
@@ -43,7 +43,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
return False
# 显式放行配置中的集成服务主机。
integration_base = (current_app.config.get("INTEGRATION_API_BASE") or "").strip()
integration_base = (IntegrationApiService.get_base_url() or "").strip()
if integration_base:
integration_host = (urlparse(integration_base).hostname or "").strip().lower()
if integration_host and host == integration_host:
@@ -76,8 +76,8 @@ def _fetch_preview_source_bytes(file_url: str):
from urllib.parse import parse_qs
headers = {}
base_url = current_app.config.get('INTEGRATION_API_BASE', '')
api_key = current_app.config.get('INTEGRATION_API_KEY', '')
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
def _resolve_latest_integration_url(raw_url: str):
dataset_id = ''
+349
View File
@@ -0,0 +1,349 @@
"""
backend/app/api/integration.py
文件用途:知识库外部集成查询接口
"""
from __future__ import annotations
from pathlib import Path
from flask import Blueprint, abort, current_app, jsonify, request, send_file
from sqlalchemy import func
from sqlalchemy.orm import joinedload
from app import db
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
integration_bp = Blueprint('integration', __name__)
def _require_integration_key():
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
if not configured:
return jsonify({'error': 'INTEGRATION_API_KEY is not configured'}), 503
if configured != incoming:
return jsonify({'error': 'Unauthorized'}), 401
return None
def _integration_base_url() -> str:
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
if explicit:
return explicit
return request.host_url.rstrip('/')
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
versions = list(getattr(document, 'versions', []) or [])
if not versions:
return None
return next((item for item in versions if item.is_current), versions[0])
def _document_query():
return (
db.session.query(KbDocument)
.options(
joinedload(KbDocument.group),
joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records),
)
.filter(KbDocument.is_deleted.is_(False))
)
def _serialize_integration_document(
document: KbDocument,
*,
version: KbDocumentVersion | None = None,
sync_record: KbDifySyncRecord | None = None,
):
version = version or _current_version(document)
if not version:
abort(404, description='No current version found.')
sync_record = sync_record or (
next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None)
or (version.sync_records[0] if getattr(version, 'sync_records', None) else None)
)
base_url = _integration_base_url()
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source'
markdown_download_url = (
f'{base_url}/api/integration/files/{document.id}/download?kind=md'
if version.cleaned_file_path or version.cleaned_preview_path
else None
)
return {
'document_id': document.id,
'knowledge_base': {
'id': document.group.id if document.group else None,
'name': document.group.name if document.group else None,
'department_id': document.group.department_id if document.group else None,
'dify_dataset_id': document.group.dify_dataset_id if document.group else None,
},
'title': document.title,
'source_filename': version.source_file_name,
'source_ext': version.source_file_ext,
'file_name': version.source_file_name,
'version_id': version.id,
'version_no': version.version_no,
'convert_status': version.status,
'sync_status': sync_record.status if sync_record else None,
'uploaded_at': version.created_at.isoformat() if version.created_at else None,
'converted_at': version.converted_at.isoformat() if version.converted_at else None,
'download_url_expires_at': None,
'source_download_url': source_download_url,
'markdown_download_url': markdown_download_url,
'markdown_download_url_expires_at': None,
'markdown_public_url': markdown_download_url,
'dify': {
'dataset_id': sync_record.dataset_id if sync_record else (document.group.dify_dataset_id if document.group else None),
'remote_document_id': sync_record.remote_document_id if sync_record else None,
'status': sync_record.status if sync_record else None,
'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None,
},
}
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
return {
'id': group.id,
'knowledge_base_id': group.id,
'name': group.name,
'description': group.description,
'department_id': group.department_id,
'dify_dataset_id': group.dify_dataset_id,
'document_count': int(document_count or 0),
'created_at': group.created_at.isoformat() if group.created_at else None,
'updated_at': group.updated_at.isoformat() if group.updated_at else None,
}
def _list_files_payload(
*,
knowledge_base_id: int | None = None,
department_id: int | None = None,
file_name: str | None = None,
) -> list[dict]:
normalized_file_name = str(file_name or '').strip().lower()
query = _document_query().order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
if knowledge_base_id is not None:
query = query.filter(KbDocument.group_id == knowledge_base_id)
if department_id is not None:
query = query.join(KbGroup, KbGroup.id == KbDocument.group_id).filter(KbGroup.department_id == department_id)
documents = query.all()
payload = []
for document in documents:
version = _current_version(document)
if not version:
continue
normalized_name = version.source_file_name.lower() if version.source_file_name else ''
if normalized_file_name and normalized_file_name not in normalized_name and normalized_file_name not in document.title.lower():
continue
payload.append(_serialize_integration_document(document, version=version))
return payload
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
if kind == 'source':
path = Path(version.source_file_path)
filename = version.source_file_name or f'document-{version.document_id}'
return path, filename
preferred = version.cleaned_file_path or version.cleaned_preview_path
if not preferred:
abort(409, description='Markdown not ready.')
path = Path(preferred)
filename = f'document-{version.document_id}-v{version.version_no}.md'
return path, filename
@integration_bp.before_request
def _verify_integration_access():
result = _require_integration_key()
if result is not None:
return result
return None
@integration_bp.route('/files/<int:file_id>', methods=['GET'])
def get_file_detail(file_id: int):
document = _document_query().filter(KbDocument.id == file_id).first()
if not document:
return jsonify({'error': 'Document not found.'}), 404
return jsonify(_serialize_integration_document(document))
@integration_bp.route('/knowledge-bases', methods=['GET'])
def list_knowledge_bases():
department_id = request.args.get('department_id', type=int)
q = str(request.args.get('q') or '').strip()
document_counts = (
db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count'))
.filter(KbDocument.is_deleted.is_(False))
.group_by(KbDocument.group_id)
.subquery()
)
query = (
db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count'))
.outerjoin(document_counts, document_counts.c.group_id == KbGroup.id)
.filter(KbGroup.is_active.is_(True))
.order_by(KbGroup.name.asc())
)
if department_id is not None:
query = query.filter(KbGroup.department_id == department_id)
if q:
query = query.filter(KbGroup.name.ilike(f'%{q}%'))
rows = query.all()
return jsonify({'data': [_serialize_knowledge_base(group, document_count=document_count) for group, document_count in rows]})
@integration_bp.route('/files', methods=['GET'])
def list_files():
knowledge_base_id = request.args.get('knowledge_base_id', type=int)
department_id = request.args.get('department_id', type=int)
file_name = request.args.get('file_name')
return jsonify({'data': _list_files_payload(
knowledge_base_id=knowledge_base_id,
department_id=department_id,
file_name=file_name,
)})
@integration_bp.route('/knowledge-bases/<int:knowledge_base_id>/files', methods=['GET'])
def list_files_for_knowledge_base(knowledge_base_id: int):
return jsonify({'data': _list_files_payload(
knowledge_base_id=knowledge_base_id,
file_name=request.args.get('file_name'),
)})
@integration_bp.route('/dify-file', methods=['GET'])
def get_file_detail_by_dify():
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
if not remote_document_id:
return jsonify({'error': 'remote_document_id is required'}), 400
record_query = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.options(
joinedload(KbDifySyncRecord.document_version)
.joinedload(KbDocumentVersion.document)
.joinedload(KbDocument.group),
joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records),
)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.remote_document_id == remote_document_id,
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
)
if dataset_id:
record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id)
record = record_query.first()
version = record.document_version if record else None
document = version.document if version else None
if not document:
return jsonify({'error': 'No local file mapping found for the given Dify document.'}), 404
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
@integration_bp.route('/dify-files/resolve', methods=['POST'])
def resolve_files_by_dify():
data = request.get_json(silent=True) or {}
items = data.get('items') if isinstance(data.get('items'), list) else []
if not items:
return jsonify({'data': []})
remote_ids = sorted({
str(item.get('remote_document_id') or '').strip()
for item in items
if isinstance(item, dict) and str(item.get('remote_document_id') or '').strip()
})
dataset_ids = sorted({
str(item.get('dataset_id') or '').strip()
for item in items
if isinstance(item, dict) and str(item.get('dataset_id') or '').strip()
})
if not remote_ids:
return jsonify({'data': []})
query = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.options(
joinedload(KbDifySyncRecord.document_version)
.joinedload(KbDocumentVersion.document)
.joinedload(KbDocument.group),
joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records),
)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.remote_document_id.in_(remote_ids),
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
)
if dataset_ids:
query = query.filter(
(KbDifySyncRecord.dataset_id.in_(dataset_ids)) | (KbDifySyncRecord.dataset_id.is_(None))
)
records = query.all()
records_by_key: dict[tuple[str | None, str], KbDifySyncRecord] = {}
records_by_remote: dict[str, KbDifySyncRecord] = {}
for record in records:
key = (record.dataset_id, record.remote_document_id)
records_by_key.setdefault(key, record)
records_by_remote.setdefault(record.remote_document_id, record)
payload = []
for item in items:
if not isinstance(item, dict):
continue
requested_dataset_id = str(item.get('dataset_id') or '').strip() or None
requested_remote_document_id = str(item.get('remote_document_id') or '').strip()
if not requested_remote_document_id:
continue
record = records_by_key.get((requested_dataset_id, requested_remote_document_id))
if record is None and requested_dataset_id is None:
record = records_by_remote.get(requested_remote_document_id)
version = record.document_version if record else None
document = version.document if version else None
payload.append({
'request': {
'dataset_id': requested_dataset_id,
'remote_document_id': requested_remote_document_id,
},
'found': bool(document),
'document': _serialize_integration_document(document, version=version, sync_record=record) if document else None,
})
return jsonify({'data': payload})
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
def download_file(file_id: int):
kind = str(request.args.get('kind') or 'md').strip().lower()
document = _document_query().filter(KbDocument.id == file_id).first()
if not document:
return jsonify({'error': 'Document not found.'}), 404
version = _current_version(document)
if not version:
return jsonify({'error': 'No version found.'}), 404
path, filename = _resolve_download_path(version, kind)
if not path.exists():
return jsonify({'error': 'File not found on disk.'}), 404
return send_file(path, as_attachment=True, download_name=filename)
File diff suppressed because it is too large. Load diff
+157 -98
View File
@@ -5,7 +5,7 @@ from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_even
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.auth_jwt import get_current_user as _auth_current_user
from app.auth_jwt import issue_local_access_token
from sqlalchemy.exc import IntegrityError, OperationalError
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
from sqlalchemy import and_, or_, inspect, insert
from datetime import datetime, timedelta
import uuid
@@ -147,6 +147,20 @@ def _get_current_user():
"""
return _auth_current_user()
def _run_db_with_retry(operation, *, label: str):
try:
return operation()
except (OperationalError, DatabaseError) as exc:
current_app.logger.warning('%s failed on first attempt: %s', label, exc)
db.session.rollback()
db.session.remove()
try:
db.engine.dispose()
except Exception as dispose_exc:
current_app.logger.warning('%s dispose engine failed: %s', label, dispose_exc)
return operation()
def _is_wecom_configured():
return all([
current_app.config.get('WECOM_ENABLED'),
@@ -891,7 +905,7 @@ def login():
'error_code': 'PASSWORD_LOGIN_DISABLED',
}), 403
try:
def _attempt_login():
data = request.get_json() or {}
username = data.get('username')
password = data.get('password')
@@ -919,12 +933,28 @@ def login():
_write_login_audit('password', 'success', user=user)
db.session.commit()
return jsonify(_build_login_payload(user, 'password'))
try:
return _attempt_login()
except OperationalError as e:
print(f"Database connection error: {e}")
return jsonify({'error': 'Database connection failed'}), 503
db.session.rollback()
db.session.remove()
try:
return _attempt_login()
except (OperationalError, DatabaseError) as retry_exc:
current_app.logger.warning('Password login retry failed: %s', retry_exc)
return jsonify({'error': 'Database connection failed'}), 503
except DatabaseError as e:
db.session.rollback()
db.session.remove()
try:
return _attempt_login()
except (OperationalError, DatabaseError) as retry_exc:
current_app.logger.warning('Password login retry failed: %s', retry_exc)
return jsonify({'error': 'Database connection failed'}), 503
except Exception as e:
db.session.rollback()
print(f"Login error: {e}")
current_app.logger.exception('Login error: %s', e)
return jsonify({'error': 'Internal server error'}), 500
@@ -1704,64 +1734,76 @@ def home():
user = _get_current_user()
if not user:
return jsonify({'error': 'Unauthorized'}), 401
# Get all agents available to user (including public ones)
if user.role == 'admin':
agents = db.session.query(Agent).filter_by(is_active=True).all()
else:
# User permissions
agents = user.agents
# Favorites
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
favorite_ids = [f.agent_id for f in favorites]
# Quick Questions (Global + User specific)
qqs = db.session.query(QuickQuestion).filter(
(QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)
).all()
# Layout
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
layout = layout_config.layout if layout_config else {}
# Embedded agents
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
embedded_agents = []
for rel in embedded_rel:
agent = db.session.get(Agent, rel.agent_id)
if agent:
embedded_agents.append({
def _load_home_payload():
# Get all agents available to user (including public ones)
if user.role == 'admin':
agent_rows = (
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url)
.filter(Agent.is_active.is_(True))
.all()
)
else:
# User permissions
agent_rows = [{
'id': agent.id,
'name': agent.name,
'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None
})
'description': agent.description,
'icon_url': agent.icon_url,
} for agent in user.agents]
return jsonify({
'user': {
'id': user.id,
'username': user.username,
'role': user.role,
'default_agent_id': user.default_agent_id,
'language': user.language,
'theme_preference': user.theme_preference or 'system',
},
'agents': [{
'id': a.id,
'name': a.name,
'description': a.description,
'icon_url': a.icon_url
} for a in agents],
'favorite_agent_ids': favorite_ids,
'quick_questions': [{
'id': q.id,
'title': q.title,
'question': q.question,
'agent_id': q.agent_id
} for q in qqs],
'embedded_agents': embedded_agents,
'layout': layout
})
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
favorite_ids = [f.agent_id for f in favorites]
qqs = db.session.query(QuickQuestion).filter(
(QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)
).all()
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
layout = layout_config.layout if layout_config else {}
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
embedded_agents = []
for rel in embedded_rel:
agent = db.session.get(Agent, rel.agent_id)
if agent:
embedded_agents.append({
'id': agent.id,
'name': agent.name,
'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None
})
return jsonify({
'user': {
'id': user.id,
'username': user.username,
'role': user.role,
'default_agent_id': user.default_agent_id,
'language': user.language,
'theme_preference': user.theme_preference or 'system',
},
'agents': [{
'id': a.id if hasattr(a, 'id') else a['id'],
'name': a.name if hasattr(a, 'name') else a['name'],
'description': a.description if hasattr(a, 'description') else a['description'],
'icon_url': a.icon_url if hasattr(a, 'icon_url') else a['icon_url']
} for a in agent_rows],
'favorite_agent_ids': favorite_ids,
'quick_questions': [{
'id': q.id,
'title': q.title,
'question': q.question,
'agent_id': q.agent_id
} for q in qqs],
'embedded_agents': embedded_agents,
'layout': layout
})
try:
return _run_db_with_retry(_load_home_payload, label='user.home')
except (OperationalError, DatabaseError) as exc:
current_app.logger.warning('user.home retry failed: %s', exc)
return jsonify({'error': 'Database connection failed'}), 503
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
def toggle_favorite(agent_id: int):
@@ -1872,41 +1914,45 @@ def user_profile():
# PUT
data = request.get_json() or {}
if 'real_name' in data:
user.real_name = data['real_name']
if 'phone_number' in data:
user.phone_number = data['phone_number']
if 'language' in data:
user.language = data['language']
if 'theme_preference' in data:
if data['theme_preference'] not in ['light', 'dark', 'system']:
return jsonify({'error': 'Invalid theme preference'}), 400
user.theme_preference = data['theme_preference']
# Allow editing email, employee_id, department
if 'email' in data:
# Check uniqueness
if data['email']:
existing = db.session.query(User).filter_by(email=data['email']).first()
if existing and existing.id != user.id:
return jsonify({'error': 'Email already exists'}), 400
user.email = data['email']
if 'employee_id' in data:
# Check uniqueness
if data['employee_id']:
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
if existing and existing.id != user.id:
return jsonify({'error': 'Employee ID already exists'}), 400
user.employee_id = data['employee_id']
if 'department' in data:
user.department = data['department']
try:
def _update_profile():
if 'real_name' in data:
user.real_name = data['real_name']
if 'phone_number' in data:
user.phone_number = data['phone_number']
if 'language' in data:
user.language = data['language']
if 'theme_preference' in data:
if data['theme_preference'] not in ['light', 'dark', 'system']:
return jsonify({'error': 'Invalid theme preference'}), 400
user.theme_preference = data['theme_preference']
if 'email' in data:
if data['email']:
existing = db.session.query(User).filter_by(email=data['email']).first()
if existing and existing.id != user.id:
return jsonify({'error': 'Email already exists'}), 400
user.email = data['email']
if 'employee_id' in data:
if data['employee_id']:
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
if existing and existing.id != user.id:
return jsonify({'error': 'Employee ID already exists'}), 400
user.employee_id = data['employee_id']
if 'department' in data:
user.department = data['department']
db.session.commit()
return jsonify({'message': 'Profile updated successfully'})
try:
return _run_db_with_retry(_update_profile, label='user.profile.update')
except (OperationalError, DatabaseError) as exc:
db.session.rollback()
current_app.logger.warning('user.profile.update retry failed: %s', exc)
return jsonify({'error': 'Database connection failed'}), 503
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
@@ -2039,17 +2085,30 @@ def get_announcements():
"""
Get active announcements (Public)
"""
try:
anns = db.session.query(Announcement).filter_by(is_active=True).order_by(Announcement.created_at.desc()).all()
def _load_announcements():
anns = (
db.session.query(
Announcement.id,
Announcement.title,
Announcement.content,
Announcement.created_at,
)
.filter(Announcement.is_active.is_(True))
.order_by(Announcement.created_at.desc())
.all()
)
return jsonify([{
'id': a.id,
'title': a.title,
'content': a.content,
'created_at': a.created_at.isoformat()
} for a in anns])
except Exception as e:
import traceback
return jsonify({'error': str(e), 'traceback': traceback.format_exc()}), 500
try:
return _run_db_with_retry(_load_announcements, label='user.announcements')
except (OperationalError, DatabaseError) as exc:
current_app.logger.warning('user.announcements retry failed: %s', exc)
return jsonify({'error': 'Database connection failed'}), 503
@user_bp.route('/announcements', methods=['POST'])
def create_announcement():