unit_grouping_demo.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. 单元分类功能演示脚本
  5. 该脚本帮助用户快速启动和测试单元分类功能
  6. """
  7. import os
  8. import sys
  9. import subprocess
  10. import time
  11. import threading
  12. from pathlib import Path
  13. def print_banner():
  14. """打印横幅"""
  15. print("=" * 70)
  16. print("单元分类功能演示")
  17. print("=" * 70)
  18. print()
  19. def check_dependencies():
  20. """检查依赖项"""
  21. print("🔍 检查依赖项...")
  22. required_packages = [
  23. 'fastapi',
  24. 'uvicorn',
  25. 'sqlalchemy',
  26. 'shapely',
  27. 'psycopg2',
  28. 'geoalchemy2'
  29. ]
  30. missing_packages = []
  31. for package in required_packages:
  32. try:
  33. __import__(package)
  34. print(f"✓ {package}")
  35. except ImportError:
  36. missing_packages.append(package)
  37. print(f"✗ {package} (缺失)")
  38. if missing_packages:
  39. print("\n❌ 缺少依赖项,请先安装:")
  40. print("conda env create -f environment.yml")
  41. print("或手动安装: pip install " + " ".join(missing_packages))
  42. return False
  43. print("✓ 所有依赖项已安装")
  44. return True
  45. def check_database_config():
  46. """检查数据库配置"""
  47. print("\n🔍 检查数据库配置...")
  48. # 回到项目根目录查找配置文件
  49. project_root = Path(__file__).parent.parent.parent
  50. config_file = project_root / "config.env"
  51. if not config_file.exists():
  52. print("❌ 配置文件 config.env 不存在")
  53. return False
  54. # 检查基本配置项
  55. required_vars = ['DB_HOST', 'DB_PORT', 'DB_NAME', 'DB_USER', 'DB_PASSWORD']
  56. try:
  57. from dotenv import load_dotenv # type: ignore
  58. load_dotenv(str(config_file))
  59. for var in required_vars:
  60. if not os.getenv(var):
  61. print(f"❌ 环境变量 {var} 未设置")
  62. return False
  63. print("✓ 数据库配置正确")
  64. return True
  65. except Exception as e:
  66. print(f"❌ 检查数据库配置时出错: {e}")
  67. return False
  68. def start_server():
  69. """启动服务器"""
  70. print("\n🚀 启动FastAPI服务器...")
  71. print("服务器将在 http://localhost:8000 启动")
  72. print("API文档地址: http://localhost:8000/docs")
  73. print("按 Ctrl+C 停止服务器")
  74. print("-" * 50)
  75. try:
  76. # 切换到项目根目录
  77. project_root = Path(__file__).parent.parent.parent
  78. os.chdir(project_root)
  79. # 使用subprocess启动uvicorn
  80. process = subprocess.Popen([
  81. sys.executable, '-m', 'uvicorn',
  82. 'main:app',
  83. '--reload',
  84. '--host', '0.0.0.0',
  85. '--port', '8000'
  86. ])
  87. # 等待服务器启动
  88. time.sleep(3)
  89. return process
  90. except Exception as e:
  91. print(f"❌ 启动服务器失败: {e}")
  92. return None
  93. def run_tests():
  94. """运行测试"""
  95. print("\n🧪 运行集成测试...")
  96. print("-" * 50)
  97. try:
  98. # 等待服务器完全启动
  99. time.sleep(2)
  100. # 运行测试脚本
  101. project_root = Path(__file__).parent.parent.parent
  102. test_file = project_root / "tests" / "integration" / "test_unit_grouping.py"
  103. if test_file.exists():
  104. subprocess.run([sys.executable, str(test_file)])
  105. else:
  106. print(f"❌ 测试文件不存在: {test_file}")
  107. except Exception as e:
  108. print(f"❌ 运行测试失败: {e}")
  109. def show_usage_info():
  110. """显示使用信息"""
  111. print("\n📖 使用说明:")
  112. print("-" * 50)
  113. print("1. 主要API端点:")
  114. print(" GET /api/unit-grouping/h_xtfx - 获取所有单元的h_xtfx分类")
  115. print(" GET /api/unit-grouping/statistics - 获取统计信息")
  116. print(" GET /api/unit-grouping/unit/{unit_id} - 获取特定单元的h_xtfx值")
  117. print()
  118. print("2. 测试示例:")
  119. print(" curl http://localhost:8000/api/unit-grouping/h_xtfx")
  120. print(" curl http://localhost:8000/api/unit-grouping/statistics")
  121. print()
  122. print("3. 查看完整API文档:")
  123. print(" http://localhost:8000/docs")
  124. print()
  125. print("4. 重新运行测试:")
  126. print(" python tests/integration/test_unit_grouping.py")
  127. print()
  128. print("5. 查看功能文档:")
  129. print(" docs/features/unit-grouping/README.md")
  130. def main():
  131. """主函数"""
  132. print_banner()
  133. # 检查依赖项
  134. if not check_dependencies():
  135. return
  136. # 检查数据库配置
  137. if not check_database_config():
  138. return
  139. # 启动服务器
  140. server_process = start_server()
  141. if not server_process:
  142. return
  143. try:
  144. # 运行测试
  145. test_thread = threading.Thread(target=run_tests)
  146. test_thread.daemon = True
  147. test_thread.start()
  148. # 等待测试完成
  149. test_thread.join(timeout=30)
  150. # 显示使用信息
  151. show_usage_info()
  152. print("\n🎉 服务器正在运行中...")
  153. print("按 Ctrl+C 退出")
  154. # 等待用户中断
  155. server_process.wait()
  156. except KeyboardInterrupt:
  157. print("\n\n👋 正在关闭服务器...")
  158. server_process.terminate()
  159. server_process.wait()
  160. print("服务器已关闭")
  161. except Exception as e:
  162. print(f"\n❌ 运行时出错: {e}")
  163. if server_process:
  164. server_process.terminate()
  165. if __name__ == "__main__":
  166. main()