Files
emailsystem/app/api/domain_routes.py
2025-02-25 19:50:00 +08:00

107 lines
6.4 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from flask import request, jsonify, current_app
from sqlalchemy.exc import IntegrityError
from . import api_bp
from ..models import get_session, Domain
# 获取所有域名
@api_bp.route("/domains", methods=["GET"])
def get_domains():
"""获取所有可用域名"""
try:
db = get_session()
try:
domains = db.query(Domain).filter_by(active=True).all()
return jsonify([domain.to_dict() for domain in domains]), 200
finally:
db.close()
except Exception as e:
current_app.logger.error(f"获取域名列表出错: {str(e)}")
return jsonify({"error": "获取域名列表失败", "details": str(e)}), 500
# 创建新域名
@api_bp.route("/domains", methods=["POST"])
def create_domain():
"""创建新域名"""
try:
data = request.json
if not data or "name" not in data:
return jsonify({"error": "缺少必要参数"}), 400
db = get_session()
try:
domain = Domain(
name=data["name"],
description=data.get("description", ""),
active=True
)
db.add(domain)
db.commit()
return jsonify({
"message": "域名创建成功",
"domain": domain.to_dict()
}), 201
except IntegrityError:
db.rollback()
return jsonify({"error": "域名已存在"}), 409
except Exception as e:
db.rollback()
raise
finally:
db.close()
except Exception as e:
current_app.logger.error(f"创建域名出错: {str(e)}")
return jsonify({"error": "创建域名失败", "details": str(e)}), 500
# 获取特定域名
@api_bp.route("/domains/<int:domain_id>", methods=["GET"])
def get_domain(domain_id):
"""获取指定ID的域名"""
try:
db = get_session()
try:
domain = db.query(Domain).filter_by(id=domain_id).first()
if not domain:
return jsonify({"error": "域名不存在"}), 404
return jsonify(domain.to_dict()), 200
finally:
db.close()
except Exception as e:
current_app.logger.error(f"获取域名详情出错: {str(e)}")
return jsonify({"error": "获取域名详情失败", "details": str(e)}), 500
# 禁用/启用域名
@api_bp.route("/domains/<int:domain_id>/toggle", methods=["PUT"])
def toggle_domain(domain_id):
"""启用或禁用指定域名"""
try:
db = get_session()
try:
domain = db.query(Domain).filter_by(id=domain_id).first()
if not domain:
return jsonify({"error": "域名不存在"}), 404
# 切换状态
domain.active = not domain.active
db.commit()
status = "启用" if domain.active else "禁用"
return jsonify({
"message": f"域名已{status}",
"domain": domain.to_dict()
}), 200
except Exception as e:
db.rollback()
raise
finally:
db.close()
except Exception as e:
current_app.logger.error(f"切换域名状态出错: {str(e)}")
return jsonify({"error": "切换域名状态失败", "details": str(e)}), 500