flask 最佳实践
Follow a modular and organized project structure. A common structure is:
project_root/ ├── app/ │ ├── init.py │ ├── models.py │ ├── views.py # Or controllers.py │ ├── forms.py │ ├── utils.py # Helper functions │ ├── api/ │ │ ├── init.py │ │ ├── routes.py │ ├── templates/ │ │ └── ... │ ├── static/ │ │ └── ... ├── tests/ │ ├── init.py │ ├── conftest.py # Fixtures for tests │ ├── test_models.py │ ├── test_views.py ├── migrations/ │ └── ... # Alembic migrations ├── venv/ # Virtual environment ├── .env # Environment variables (use with caution, not for sensitive data in production) ├── config.py # Application configuration ├── requirements.txt or pyproject.toml # Dependencies ├── run.py # Application entry point
Use Blueprints to organize routes and views into logical modules. Blueprints promote reusability and maintainability.
models.py
, views.py
, forms.py
, utils.py
, routes.py
, test_*.py
.models.py
, user authentication logic in auth.py
, and utility functions in utils.py
.__init__.py
files to make directories packages, allowing you to import modules within the directory using relative paths.Application Factory: Use the application factory pattern to create Flask application instances. This allows for different configurations for different environments (development, testing, production). python def create_app(config_name): app = Flask(name) app.config.from_object(config[config_name]) config[config_name].init_app(app)
# Initialize extensions (e.g., db, mail) here
db.init_app(app)
mail.init_app(app)
# Register blueprints
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
Blueprints: Organize application functionality into reusable blueprints. python from flask import Blueprint
bp = Blueprint('my_blueprint', name, url_prefix='/my_blueprint')
@bp.route('/route') def my_route(): return 'Hello from my_blueprint'
g
object or session variables instead.session
object to store user-specific data across requests.try...except
blocks to handle exceptions gracefully.abort()
function to raise HTTP exceptions.unittest.mock
module or a third-party mocking library like mock
.virtualenv
, venv
, or conda
pip
or pipenv
or poetry
pdb
or ipdb
cProfile
requirements.txt
or pyproject.toml
file to specify project dependencies.setuptools
or poetry
to package your application.flake8
or pylint
to enforce code style guidelines.black
or autopep8
to automatically format your code.