cors.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. """
  2. CORS配置文件
  3. 用于管理Flask应用的跨域资源共享设置
  4. """
  5. # 允许的源(前端地址)
  6. # 方案1: 允许所有源(开发环境推荐,最灵活)
  7. ALLOW_ALL_ORIGINS = True
  8. # 方案2: 允许特定网段的IP地址(生产环境推荐)
  9. ALLOWED_IP_RANGES = [
  10. "192.168.0.0/16", # 局域网IP段
  11. "10.0.0.0/8", # 内网IP段
  12. "172.16.0.0/12", # 内网IP段
  13. ]
  14. # 方案3: 允许的固定源(如果需要限制特定地址)
  15. ALLOWED_ORIGINS = [
  16. "http://localhost:5173", # Vite默认端口
  17. "http://localhost:3000", # React默认端口
  18. "http://localhost:8080", # Vue默认端口
  19. "http://127.0.0.1:5173",
  20. "http://127.0.0.1:3000",
  21. "http://127.0.0.1:8080",
  22. "http://192.168.3.218:5173", # 客户端前端地址
  23. "http://192.168.3.218:3000", # 客户端备用端口
  24. "http://192.168.3.218:8080", # 客户端备用端口
  25. # 生产环境地址(如果需要)
  26. # "https://yourdomain.com",
  27. ]
  28. # 允许的HTTP方法
  29. ALLOWED_METHODS = [
  30. "GET",
  31. "POST",
  32. "PUT",
  33. "DELETE",
  34. "OPTIONS"
  35. ]
  36. # 允许的请求头
  37. ALLOWED_HEADERS = [
  38. "Content-Type",
  39. "Authorization",
  40. "X-Requested-With",
  41. "Accept",
  42. "Origin",
  43. "Cache-Control",
  44. "X-File-Name"
  45. ]
  46. # 暴露的响应头
  47. EXPOSED_HEADERS = [
  48. "Content-Type",
  49. "Content-Length",
  50. "Content-Disposition",
  51. "X-Total-Count",
  52. "X-Content-Type-Options",
  53. "X-Frame-Options",
  54. "X-XSS-Protection"
  55. ]
  56. # CORS配置选项
  57. if ALLOW_ALL_ORIGINS:
  58. # 方案1: 允许所有源(最灵活)
  59. CORS_OPTIONS = {
  60. "resources": {r"/api/*": {"origins": "*"}},
  61. "supports_credentials": False, # 通配符时不能启用凭据
  62. "methods": ALLOWED_METHODS,
  63. "allow_headers": ALLOWED_HEADERS,
  64. "expose_headers": EXPOSED_HEADERS,
  65. "max_age": 86400, # 预检请求缓存时间(秒)
  66. "send_wildcard": True,
  67. "automatic_options": True
  68. }
  69. else:
  70. # 方案2: 使用固定源列表
  71. CORS_OPTIONS = {
  72. "resources": {r"/api/*": {"origins": ALLOWED_ORIGINS}},
  73. "supports_credentials": True,
  74. "methods": ALLOWED_METHODS,
  75. "allow_headers": ALLOWED_HEADERS,
  76. "expose_headers": EXPOSED_HEADERS,
  77. "max_age": 86400, # 预检请求缓存时间(秒)
  78. "send_wildcard": False,
  79. "automatic_options": True
  80. }