OA/APP/users.py

58 lines
2.1 KiB
Python
Raw Normal View History

2024-10-14 14:14:23 +08:00
from flask import Blueprint, jsonify, request
from app.models import User, UserDetail, UserField
from app import db
bp = Blueprint('users', __name__)
@bp.route('', methods=['GET'])
def get_users():
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 10, type=int)
users = User.query.paginate(page=page, per_page=per_page, error_out=False)
users_list = [{
'id': user.id,
'username': user.username,
'primary_department': user.primary_department.name if user.primary_department else None,
'roles': [role.name for role in user.roles]
} for user in users.items]
return jsonify({
'users': users_list,
'total': users.total,
'pages': users.pages,
'current_page': page
}), 200
@bp.route('/<int:user_id>', methods=['GET'])
def get_user_details(user_id):
user = User.query.get(user_id)
if not user:
return jsonify({'message': '用户不存在'}), 404
user_fields = UserField.query.all()
user_details = {}
for field in user_fields:
detail = UserDetail.query.filter_by(user_id=user.id, field_id=field.id).first()
user_details[field.name] = detail.value if detail else None
user_info = {
'id': user.id,
'username': user.username,
'primary_department': user.primary_department.name if user.primary_department else None,
'secondary_departments': [dept.name for dept in user.secondary_departments],
'roles': [role.name for role in user.roles],
'details': user_details,
'login_info': {
'register_time': user.login_info.register_time.isoformat(),
'login_count': user.login_info.login_count,
'last_login_time': user.login_info.last_login_time.isoformat() if user.login_info.last_login_time else None,
'is_new_user': user.login_info.is_new_user,
'has_changed_initial_password': user.login_info.has_changed_initial_password
}
}
return jsonify(user_info), 200
# 可以在这里添加更多用户相关的路由...