Flask从零构建完整标准Web项目
编辑日期: 2024-11-28 文章阅读: 次
为了从零构建一个标准的 Flask 项目,我们可以按照以下结构组织我们的项目:
flask_project/
│
├── app/
│ ├── __init__.py
│ ├── routes.py
│ ├── models.py
│ ├── forms.py
│ ├── templates/
│ │ ├── base.html
│ │ ├── index.html
│ ├── static/
│ ├── css/
│ ├── js/
│
├── venv/
│
├── config.py
│
├── run.py
│
└── requirements.txt
下面是每个文件和目录的详细代码。
1. config.py
import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///site.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
2. run.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
3. app/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config
db = SQLAlchemy()
migrate = Migrate()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
db.init_app(app)
migrate.init_app(app, db)
from app.routes import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
from app import models
4. app/routes.py
from flask import Blueprint, render_template
main = Blueprint('main', __name__)
@main.route('/')
def index():
return render_template('index.html')
5. app/models.py
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
def __repr__(self):
return f'<User {self.username}>'
6. app/forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, ValidationError, Email, EqualTo
from app.models import User
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
password2 = PasswordField(
'Repeat Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Register')
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user is not None:
raise ValidationError('Please use a different username.')
def validate_email(self, email):
user = User.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError('Please use a different email address.')
7. app/templates/base.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>{% block title %}{% endblock %} - Flask App</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<nav>
<!-- Navigation content -->
</nav>
<div class="container">
{% block content %}{% endblock %}
</div>
</body>
</html>
8. app/templates/index.html
{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome to the Flask App!</h1>
{% endblock %}
9. requirements.txt
Flask==2.0.3
Flask-WTF==1.0.0
Flask-SQLAlchemy==2.5.1
Flask-Migrate==3.1.0
10. 设置虚拟环境和安装依赖
在项目目录中运行以下命令来创建虚拟环境并安装所需的依赖项:
python3 -m venv venv
source venv/bin/activate # 对于 Windows,使用 `venv\Scripts\activate`
pip install -r requirements.txt
11. 初始化数据库
执行以下命令来初始化数据库:
flask db init
flask db migrate -m "Initial migration."
flask db upgrade
12. 运行应用
最后,运行应用程序:
python run.py
通过这些步骤,你就能创建一个标准结构的 Flask 项目,并可以根据需要扩展和修改该项目。