test_cors_config.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. #!/usr/bin/env python3
  2. """
  3. 测试CORS配置的脚本
  4. 用于验证Flask应用的跨域设置是否正确
  5. """
  6. import requests
  7. import json
  8. from datetime import datetime
  9. def test_cors_preflight():
  10. """测试CORS预检请求"""
  11. base_url = "http://company.citupro.com:5500"
  12. endpoint = "/api/data_parse/get-calendar-info"
  13. # 测试OPTIONS预检请求
  14. print("=== 测试CORS预检请求 ===")
  15. try:
  16. headers = {
  17. 'Origin': 'http://localhost:5173',
  18. 'Access-Control-Request-Method': 'GET',
  19. 'Access-Control-Request-Headers': 'Content-Type'
  20. }
  21. response = requests.options(f"{base_url}{endpoint}", headers=headers)
  22. print(f"预检请求状态码: {response.status_code}")
  23. print(f"预检请求响应头:")
  24. for key, value in response.headers.items():
  25. if key.lower().startswith('access-control'):
  26. print(f" {key}: {value}")
  27. if response.status_code == 200:
  28. print("✅ 预检请求成功")
  29. else:
  30. print("❌ 预检请求失败")
  31. except Exception as e:
  32. print(f"❌ 预检请求异常: {e}")
  33. def test_cors_actual_request():
  34. """测试实际的跨域请求"""
  35. base_url = "http://company.citupro.com:5500"
  36. endpoint = "/api/data_parse/get-calendar-info"
  37. print("\n=== 测试实际跨域请求 ===")
  38. try:
  39. # 使用当前日期
  40. today = datetime.now().strftime("%Y-%m-%d")
  41. headers = {
  42. 'Origin': 'http://localhost:5173',
  43. 'Content-Type': 'application/json'
  44. }
  45. response = requests.get(
  46. f"{base_url}{endpoint}?date={today}",
  47. headers=headers
  48. )
  49. print(f"实际请求状态码: {response.status_code}")
  50. print(f"响应头:")
  51. for key, value in response.headers.items():
  52. if key.lower().startswith('access-control'):
  53. print(f" {key}: {value}")
  54. if response.status_code == 200:
  55. print("✅ 实际请求成功")
  56. try:
  57. data = response.json()
  58. print(f"响应数据: {json.dumps(data, ensure_ascii=False, indent=2)}")
  59. except:
  60. print(f"响应内容: {response.text}")
  61. else:
  62. print("❌ 实际请求失败")
  63. print(f"响应内容: {response.text}")
  64. except Exception as e:
  65. print(f"❌ 实际请求异常: {e}")
  66. def test_cors_headers():
  67. """测试CORS响应头"""
  68. base_url = "http://company.citupro.com:5500"
  69. endpoint = "/api/data_parse/get-calendar-info"
  70. print("\n=== 测试CORS响应头 ===")
  71. try:
  72. today = datetime.now().strftime("%Y-%m-%d")
  73. response = requests.get(f"{base_url}{endpoint}?date={today}")
  74. print("所有响应头:")
  75. for key, value in response.headers.items():
  76. print(f" {key}: {value}")
  77. # 检查关键的CORS头部
  78. cors_headers = [
  79. 'Access-Control-Allow-Origin',
  80. 'Access-Control-Allow-Methods',
  81. 'Access-Control-Allow-Headers',
  82. 'Access-Control-Allow-Credentials'
  83. ]
  84. print("\nCORS相关头部:")
  85. for header in cors_headers:
  86. value = response.headers.get(header, '未设置')
  87. print(f" {header}: {value}")
  88. except Exception as e:
  89. print(f"❌ 测试响应头异常: {e}")
  90. if __name__ == "__main__":
  91. print("开始测试CORS配置...")
  92. print(f"测试时间: {datetime.now()}")
  93. print(f"目标服务器: http://company.citupro.com:5500")
  94. print(f"模拟前端: http://localhost:5173")
  95. print("=" * 50)
  96. test_cors_preflight()
  97. test_cors_actual_request()
  98. test_cors_headers()
  99. print("\n" + "=" * 50)
  100. print("CORS配置测试完成")