{{ message }}
{% endfor %}
{% endif %}
{% endwith %}
{% block content %}
{% endblock %}
以下是一个带有登录界面和主页的 Flask 示例项目,采用清晰的项目结构,符合规范,并包含全面的代码示例:
my_flask_app/
├── app/
│ ├── __init__.py
│ ├── forms.py
│ ├── models.py
│ ├── templates/
│ │ ├── base.html
│ │ ├── index.html
│ │ ├── login.html
│ ├── static/
│ │ ├── style.css
│ └── views.py
├── config.py
├── run.py
└── venv/
app/__init__.py
:Flask 应用的初始化文件。
app/forms.py
:Flask-WTF 表单定义。
app/models.py
:SQLAlchemy 数据库模型。
app/templates/
:Jinja2 模板文件。
app/static/
:静态文件(CSS、JS、图片等)。
app/views.py
:视图函数和路由。
config.py
:应用配置文件。
run.py
:运行应用的脚本。
venv/
:Python 虚拟环境。
config.py
import os
class Config:
SECRET_KEY = 'your_secret_key' # 设置密钥
SQLALCHEMY_DATABASE_URI = 'sqlite:///site.db' # 使用 SQLite 数据库
SQLALCHEMY_TRACK_MODIFICATIONS = False
app/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import Config
db = SQLAlchemy()
login_manager = LoginManager()
def create_app():
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
login_manager.init_app(app)
from app.views import main_bp
app.register_blueprint(main_bp)
return app
app/models.py
from app import db, login_manager
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
app/forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Log In')
app/views.py
from flask import render_template, redirect, url_for, request, flash, current_app, Blueprint
from app import db, login_manager
from app.forms import LoginForm
from app.models import User
from flask_login import login_user, logout_user, login_required
main_bp = Blueprint('main', __name__)
@main_bp.route('/')
def home():
return redirect(url_for('main.login'))
@main_bp.route('/logout')
def log_out():
return redirect(url_for('main.login'))
@main_bp.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user and user.password == form.password.data:
login_user(user)
return redirect(url_for('main.index'))
else:
flash('Login Failed. Check your credentials.', 'danger')
return render_template('login.html', title='Login', form=form)
@main_bp.route('/index', methods=['GET', 'POST'])
@login_required
def index():
return render_template('index.html', title='Home')
app/templates/base.html
{% block title %}Flask App{% endblock %}
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
{{ message }}
{% endfor %}
{% endif %}
{% endwith %}
{% block content %}
{% endblock %}
app/templates/login.html
{% extends "base.html" %}
{% block title %}Login{% endblock %}
{% block content %}
Login
{% endblock %}
app/templates/index.html
{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block content %}
Welcome to the Home Page!
You are logged in as {{ current_user.username }}.
退出登录
{% endblock %}
app/static/style.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
.content {
width: 50%;
margin: 20px auto;
padding: 20px;
background: white;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h1 {
text-align: center;
color: #333;
}
form div {
margin: 15px 0;
}
input[type="text"], input[type="password"] {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
.alert {
padding: 15px;
margin-bottom: 20px;
border-radius: 4px;
text-align: center;
}
.alert.danger {
background-color: #ffe6e6;
color: #b22222;
border-left: 4px solid #cd5c5c;
}
.alert.success {
background-color: #e6ffe6;
color: #228b22;
border-left: 4px solid #228b22;
}
run.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
创建虚拟环境并激活:
python -m venv venv
source venv/bin/activate # Linux/macOS
.\venv\Scripts\activate # Windows
安装依赖:
pip install flask flask-sqlalchemy flask-login flask-wtf
初始化数据库:
在 app/__init__.py
中添加以下代码创建数据库:
with app.app_context():
db.create_all()
或者在 Python shell 中运行:
from app import create_app, db
app = create_app()
with app.app_context():
db.create_all()
创建测试用户: 使用 Flask shell 创建一个测试用户,例如:
from app import User
user = User(username='testuser', password='password')
db.session.add(user)
db.session.commit()
python run.py
然后访问:
登录页面:http://127.0.0.1:5000/login
主页:http://127.0.0.1:5000/index
(需要先登录)
用户登录(/login
):
利用 Flask-WTF 表单验证
用户认证和会话管理(Flask-Login)
主页(/index
):
显示欢迎信息
退出功能 (/logout
)
数据库支持:
使用 SQLite
基于 SQLAlchemy 的 ORM
模板引擎:
使用 Jinja2 模板继承
安全性:
请求表单验证
密码存储(这里使用明文密码,请勿用于生产环境)
CSRF 保护
静态文件支持:
CSS 样式
项目结构清晰:
符合 Flask 最佳实践
分层设计(模板、视图、模型)