# -*- coding: utf-8 -*-
"""
高兼容性Flask Web服务器
监听本地50000端口,返回"Hello World!"
解决以下常见问题:
- No root path can be found for the provided module 'builtins'
- 'NoneType' object is not iterable
方法:
- 强制指定 root_path 和 instance_path
- 使用绝对路径作为根目录
- 捕获并打印详细错误信息
"""
import sys
import os
# 尝试导入Flask,并捕获可能的导入错误
try:
from flask import Flask
except ImportError as e:
print(f"Flask导入失败: {e}")
print("请安装Flask: pip install flask")
sys.exit(1)
# ==================== 配置 ====================
HOST = '0.0.0.0'
PORT = 50000
DEBUG = False
def get_safe_root_path():
"""
获取一个绝对存在的根路径,作为Flask的root_path
优先级:__file__ 所在目录 -> 当前工作目录 -> 临时目录
"""
# 方法1:尝试获取__file__所在的目录(常规情况)
try:
if '__file__' in globals():
script_dir = os.path.dirname(os.path.abspath(__file__))
if script_dir and os.path.exists(script_dir):
return script_dir
except Exception:
pass
# 方法2:使用当前工作目录
cwd = os.getcwd()
if cwd and os.path.exists(cwd):
return cwd
# 方法3:使用临时目录(保底)
import tempfile
temp_dir = tempfile.gettempdir()
if temp_dir and os.path.exists(temp_dir):
return temp_dir
# 最后保底:返回当前目录字符串(即使不存在,Flask也可能接受)
return '.'
def create_app():
"""
创建Flask应用实例,显式提供所有必要路径
"""
root_path = get_safe_root_path()
# instance_path 也显式指定为 root_path 下的 instance 目录,避免自动检测失败
instance_path = os.path.join(root_path, 'instance')
# 如果 instance 目录不存在,创建一个(避免某些环境下因目录缺失导致问题)
try:
if not os.path.exists(instance_path):
os.makedirs(instance_path, exist_ok=True)
except Exception:
# 如果无法创建,则使用 None,让Flask处理
instance_path = None
# 创建 Flask 应用,强制指定 root_path 和 instance_relative_config
# 注意:Flask 2.3+ 支持 instance_relative_config,但这里我们显式传递 instance_path
app = Flask(
__name__,
root_path=root_path,
instance_path=instance_path,
instance_relative_config=False # 避免依赖 instance 文件夹
)
# 定义路由
@app.route('/')
def hello_world():
return "Hello World!"
return app
def main():
print("=" * 60)
print("高兼容性Flask Web服务器")
print("=" * 60)
print()
# 打印调试信息,帮助定位问题
print("环境信息:")
print(f" Python版本: {sys.version}")
print(f" Flask版本: {Flask.__version__ if hasattr(Flask, '__version__') else '未知'}")
print(f" 当前工作目录: {os.getcwd()}")
print(f" __file__ 属性: {globals().get('__file__', '不存在')}")
print(f" 安全根路径: {get_safe_root_path()}")
print()
app = create_app()
try:
print(f"正在启动服务器...")
print(f"监听地址: {HOST}:{PORT}")
print("请在浏览器中访问: http://localhost:50000/ 或 http://127.0.0.1:50000/")
print("按 Ctrl+C 可停止服务器")
print("-" * 60)
# 运行服务器
app.run(host=HOST, port=PORT, debug=DEBUG)
return True
except OSError as e:
if "Address already in use" in str(e):
print(f"错误:端口 {PORT} 已被占用,请关闭占用程序或更换端口。")
else:
print(f"启动服务器时发生操作系统错误: {e}")
return False
except Exception as e:
print(f"启动服务器时发生未知错误: {e}")
import traceback
traceback.print_exc()
return False