Compare commits

..

3 Commits

Author SHA1 Message Date
4a46e7d2f5 fix(backend): 修正默认数据库用户名及调试模式配置
- 将默认数据库用户名从 your_user 改为 postgresql,明确用户名字段说明
- 修改 .env.example 中 DEBUG 默认为 True,方便本地调试
- 更新 deploy-docker-compose.sh 脚本中 DEBUG 默认值为 True,保持一致性
- 保持数据库连接字符串格式正确,确保环境变量配置一致
2026-02-28 17:53:30 +08:00
b5f8a5f20c feat: add .env file for deployment configuration 2026-02-28 17:27:07 +08:00
58fa45be8e fix: auto-create .env file during deployment 2026-02-28 17:26:03 +08:00
5 changed files with 116 additions and 10 deletions

2
.gitignore vendored
View File

@@ -56,7 +56,7 @@ logs/
backend/logs/
# Environment
.env
# .env # 已注释,允许提交
.env.local
# OS

10
backend/.env Normal file
View File

@@ -0,0 +1,10 @@
# 环境变量配置
# 数据库配置 (PostgreSQL)
DATABASE_URL=postgresql+asyncpg://postgresql:Jchl1528@192.168.110.252:15432/hospital_performance
# JWT 配置
SECRET_KEY=test-secret-key-for-development-only-min-32-chars
# 调试模式
DEBUG=True

View File

@@ -3,10 +3,11 @@
# 数据库配置 (PostgreSQL)
# 生产环境请修改为实际的数据库连接信息
# 格式: postgresql+asyncpg://用户名:密码@主机:端口/数据库名
DATABASE_URL=postgresql+asyncpg://your_user:your_password@your_host:15432/hospital_performance
# 注意: 用户名是 postgresql 不是 postgres
DATABASE_URL=postgresql+asyncpg://postgresql:your_password@your_host:15432/hospital_performance
# JWT 配置
SECRET_KEY=your-secret-key-change-in-production-min-32-characters
# 调试模式
DEBUG=False
DEBUG=True

View File

@@ -0,0 +1,77 @@
"""
数据库连接测试脚本
"""
import asyncio
import os
import sys
from pathlib import Path
# 添加项目根目录到路径
sys.path.insert(0, str(Path(__file__).parent))
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine
async def test_connection():
"""测试数据库连接"""
print("=" * 50)
print("数据库连接诊断")
print("=" * 50)
# 1. 显示当前工作目录
print(f"\n1. 当前工作目录: {os.getcwd()}")
# 2. 检查 .env 文件
env_path = Path(__file__).parent / ".env"
print(f"2. .env 文件路径: {env_path}")
print(f" .env 文件存在: {env_path.exists()}")
if env_path.exists():
print(f" .env 文件内容:")
with open(env_path) as f:
for line in f:
if "PASSWORD" in line.upper() or "SECRET" in line.upper():
# 隐藏敏感信息
print(f" {line.strip()[:30]}***")
else:
print(f" {line.strip()}")
# 3. 加载配置
print("\n3. 加载配置:")
from app.core.config import settings
print(f" DATABASE_URL: {settings.DATABASE_URL[:50]}***")
print(f" DEBUG: {settings.DEBUG}")
# 4. 测试数据库连接
print("\n4. 测试数据库连接:")
try:
engine = create_async_engine(settings.DATABASE_URL, echo=True)
async with engine.connect() as conn:
result = await conn.execute(text("SELECT 1"))
print(" ✅ 数据库连接成功!")
await engine.dispose()
except Exception as e:
print(f" ❌ 数据库连接失败: {type(e).__name__}: {e}")
# 5. 测试其他可能的连接字符串
print("\n5. 测试备选连接字符串:")
test_urls = [
"postgresql+asyncpg://postgresql:Jchl1528@192.168.110.252:15432/hospital_performance",
"postgresql+asyncpg://postgres:Jchl1528@192.168.110.252:15432/hospital_performance",
]
for url in test_urls:
try:
engine = create_async_engine(url)
async with engine.connect() as conn:
result = await conn.execute(text("SELECT 1"))
print(f" ✅ 连接成功: {url[:40]}***")
await engine.dispose()
break
except Exception as e:
print(f" ❌ 失败: {str(e)[:50]}")
if __name__ == "__main__":
asyncio.run(test_connection())

View File

@@ -21,7 +21,7 @@ export DATABASE_USER="${DATABASE_USER:-postgresql}"
export DATABASE_PASSWORD="${DATABASE_PASSWORD:-Jchl1528}"
export DATABASE_NAME="${DATABASE_NAME:-hospital_performance}"
export SECRET_KEY="${SECRET_KEY:-change-this-secret-key-in-production}"
export DEBUG="${DEBUG:-False}"
export DEBUG="${DEBUG:-True}"
# 构建完整的 DATABASE_URL后端使用此变量
export DATABASE_URL="postgresql+asyncpg://${DATABASE_USER}:${DATABASE_PASSWORD}@${DATABASE_HOST}:${DATABASE_PORT}/${DATABASE_NAME}"
@@ -77,7 +77,25 @@ fi
echo "✅ 旧服务已停止"
# ================= Step 3: 安装依赖并部署后端 =================
# ================= Step 3: 创建环境配置 =================
echo "========== 创建环境配置 =========="
cd "${PROJECT_DIR}/backend"
# 创建 .env 文件
cat > .env <<ENVEOF
# 数据库配置
DATABASE_URL=${DATABASE_URL}
# JWT 配置
SECRET_KEY=${SECRET_KEY}
# 调试模式
DEBUG=${DEBUG}
ENVEOF
echo "✅ 环境配置已创建"
# ================= Step 4: 安装依赖并部署后端 =================
echo "========== 部署后端 =========="
cd "${PROJECT_DIR}/backend"
@@ -105,7 +123,7 @@ mkdir -p logs
nohup venv/bin/uvicorn app.main:app --host 0.0.0.0 --port ${BACKEND_PORT} --workers 4 > logs/backend.log 2>&1 &
echo "✅ 后端服务已启动,端口 ${BACKEND_PORT}"
# ================= Step 4: 构建前端 =================
# ================= Step 5: 构建前端 =================
echo "========== 构建前端 =========="
cd "${PROJECT_DIR}/frontend"
@@ -123,7 +141,7 @@ echo "构建前端项目..."
npm run build
echo "✅ 前端构建完成"
# ================= Step 5: 部署前端到 Nginx =================
# ================= Step 6: 部署前端到 Nginx =================
echo "========== 部署前端 =========="
NGINX_HTML="/var/www/hospital_performance_html"
mkdir -p ${NGINX_HTML}
@@ -156,7 +174,7 @@ echo "重启 Nginx..."
systemctl restart nginx || nginx -s reload || true
echo "✅ 前端部署完成"
# ================= Step 6: 等待并健康检查 =================
# ================= Step 7: 等待并健康检查 =================
echo "========== 执行健康检查 =========="
echo "等待服务启动..."
sleep 10
@@ -181,7 +199,7 @@ while [ $attempt -le $max_attempts ]; do
fi
done
# ================= Step 7: 查看状态 =================
# ================= Step 8: 查看状态 =================
echo "========== 服务状态 =========="
echo "后端进程:"
ps -ef | grep "uvicorn.*app.main:app" | grep -v grep
@@ -189,7 +207,7 @@ echo ""
echo "Nginx 状态:"
systemctl status nginx --no-pager || true
# ================= Step 8: 完成 =================
# ================= Step 9: 完成 =================
echo "✅ 部署完成"
echo "========================================"