Add Python to PATH# 打开命令提示符或PowerShell
python --version
# 或
python3 --version
# 检查是否已安装Python
which python3
# 如果未安装,使用包管理器安装
# Ubuntu/Debian:
sudo apt update
sudo apt install python3 python3-pip
# macOS (使用Homebrew):
brew install python@3.9
虚拟环境是Python项目的最佳实践,可以隔离不同项目的依赖包。
# 创建项目目录
mkdir myflaskapp
cd myflaskapp
# 创建虚拟环境
python -m venv venv
# 激活虚拟环境
# Windows:
venv\Scripts\activate
# macOS/Linux:
source venv/bin/activate
(venv),表示已在虚拟环境中
# 确保虚拟环境已激活
pip install flask
# 验证安装
python -c "import flask; print(f'Flask版本: {flask.__version__}')"
# Flask扩展包
pip install flask-sqlalchemy # 数据库ORM
pip install flask-wtf # 表单处理
pip install flask-login # 用户认证
pip install flask-migrate # 数据库迁移
# 查看已安装的包
pip list
myflaskapp/
├── app/
│ ├── __init__.py
│ ├── routes.py
│ └── templates/
│ └── index.html
├── venv/ # 虚拟环境目录
├── config.py # 配置文件
├── requirements.txt # 依赖列表
└── run.py # 启动文件
# 生成依赖文件
pip freeze > requirements.txt
# 查看文件内容
cat requirements.txt
click==8.1.3
Flask==2.3.2
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.3
Werkzeug==2.3.6
from flask import Flask
def create_app():
app = Flask(__name__)
# 加载配置
app.config.from_pyfile('../config.py')
# 注册蓝图(如果有)
from app.routes import main
app.register_blueprint(main)
return app
from flask import Blueprint, render_template
main = Blueprint('main', __name__)
@main.route('/')
def index():
return render_template('index.html', title='欢迎页')
@main.route('/hello/<name>')
def hello(name):
return f'Hello, {name}!'
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<h1 class="text-primary">🎉 Flask应用运行成功!</h1>
<p class="lead">这是一个简单的Flask应用示例</p>
<div class="alert alert-success">
<strong>当前URL:</strong> {{ request.url }}
</div>
<a href="/hello/World" class="btn btn-primary">打个招呼</a>
</div>
</body>
</html>
# 基础配置
DEBUG = True
SECRET_KEY = 'your-secret-key-here'
# 数据库配置(示例)
SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(
host='0.0.0.0', # 允许外部访问
port=5000,
debug=True # 调试模式
)
# 确保在项目根目录
python run.py
可能是系统权限问题,可以尝试:
# Windows PowerShell以管理员运行
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
检查防火墙设置,或修改运行配置:
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, debug=True)