test_flexible_cors.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #!/usr/bin/env python3
  2. """
  3. 测试灵活CORS配置的脚本
  4. 用于验证任意前端地址的跨域请求是否正常工作
  5. """
  6. import requests
  7. import json
  8. from datetime import datetime
  9. import random
  10. def generate_random_origin():
  11. """生成随机的Origin地址用于测试"""
  12. # 随机IP地址
  13. ip_ranges = [
  14. "192.168.1", "192.168.2", "192.168.3", "192.168.4", "192.168.5",
  15. "10.0.1", "10.0.2", "10.0.3", "10.0.4", "10.0.5",
  16. "172.16.1", "172.16.2", "172.16.3", "172.16.4", "172.16.5"
  17. ]
  18. # 随机端口
  19. ports = [3000, 5173, 8080, 3001, 5174, 8081, 4000, 5000, 6000]
  20. ip_base = random.choice(ip_ranges)
  21. ip_last = random.randint(1, 254)
  22. port = random.choice(ports)
  23. return f"http://{ip_base}.{ip_last}:{port}"
  24. def test_flexible_cors():
  25. """测试灵活的CORS配置"""
  26. base_url = "http://company.citupro.com:5500"
  27. endpoint = "/api/data_parse/get-calendar-info"
  28. print("=== 测试灵活CORS配置 ===")
  29. print(f"测试时间: {datetime.now()}")
  30. print(f"目标服务器: {base_url}")
  31. print(f"测试端点: {endpoint}")
  32. print("=" * 60)
  33. # 测试1: 测试固定Origin
  34. print("1. 测试固定Origin...")
  35. test_origins = [
  36. "http://localhost:5173",
  37. "http://192.168.3.218:5173",
  38. "http://10.0.0.1:3000",
  39. "http://172.16.1.100:8080"
  40. ]
  41. for origin in test_origins:
  42. print(f"\n 测试Origin: {origin}")
  43. try:
  44. headers = {
  45. 'Origin': origin,
  46. 'Access-Control-Request-Method': 'GET'
  47. }
  48. response = requests.options(f"{base_url}{endpoint}", headers=headers)
  49. print(f" OPTIONS状态码: {response.status_code}")
  50. cors_origin = response.headers.get('Access-Control-Allow-Origin', '未设置')
  51. print(f" Access-Control-Allow-Origin: {cors_origin}")
  52. if cors_origin == origin or cors_origin == '*':
  53. print(" ✅ CORS配置正确")
  54. else:
  55. print(" ❌ CORS配置有问题")
  56. except Exception as e:
  57. print(f" ❌ 测试失败: {e}")
  58. # 测试2: 测试随机Origin
  59. print("\n2. 测试随机Origin...")
  60. for i in range(3):
  61. random_origin = generate_random_origin()
  62. print(f"\n 测试随机Origin {i+1}: {random_origin}")
  63. try:
  64. headers = {
  65. 'Origin': random_origin,
  66. 'Access-Control-Request-Method': 'GET'
  67. }
  68. response = requests.options(f"{base_url}{endpoint}", headers=headers)
  69. print(f" OPTIONS状态码: {response.status_code}")
  70. cors_origin = response.headers.get('Access-Control-Allow-Origin', '未设置')
  71. print(f" Access-Control-Allow-Origin: {cors_origin}")
  72. if cors_origin == random_origin or cors_origin == '*':
  73. print(" ✅ 随机Origin支持正确")
  74. else:
  75. print(" ❌ 随机Origin支持有问题")
  76. except Exception as e:
  77. print(f" ❌ 测试失败: {e}")
  78. # 测试3: 测试实际GET请求
  79. print("\n3. 测试实际GET请求...")
  80. test_origin = "http://192.168.100.200:9999" # 一个不常见的地址
  81. print(f" 测试Origin: {test_origin}")
  82. try:
  83. today = datetime.now().strftime("%Y-%m-%d")
  84. headers = {'Origin': test_origin}
  85. response = requests.get(f"{base_url}{endpoint}?date={today}", headers=headers)
  86. print(f" GET状态码: {response.status_code}")
  87. if response.status_code == 200:
  88. print(" ✅ GET请求成功")
  89. cors_origin = response.headers.get('Access-Control-Allow-Origin', '未设置')
  90. print(f" Access-Control-Allow-Origin: {cors_origin}")
  91. else:
  92. print(f" ❌ GET请求失败: {response.text}")
  93. except Exception as e:
  94. print(f" ❌ GET请求异常: {e}")
  95. print("\n" + "=" * 60)
  96. print("测试完成!")
  97. print("\n如果看到✅,说明CORS配置灵活且正确。")
  98. print("如果看到❌,请检查:")
  99. print("1. Flask应用是否已重启")
  100. print("2. 新的灵活CORS配置是否生效")
  101. print("3. 是否启用了ALLOW_ALL_ORIGINS")
  102. if __name__ == "__main__":
  103. test_flexible_cors()