從0到1:Flask項目開發流程與最佳實踐

一、什麼是Flask?

Flask是一個輕量級的Python Web框架,它用簡潔的代碼實現了Web應用的核心功能,同時保持了高度的靈活性。相比Django的“電池內置”理念,Flask更像一個“工具箱”,你可以按需選擇組件(如ORM、表單處理等),非常適合初學者入門Web開發,也適合快速開發中小型項目。

二、開發環境準備

1. 安裝Python

首先確保你的電腦已安裝Python(推薦3.7+版本)。
- 檢查安裝:打開終端/命令行,輸入 python --versionpython3 --version,顯示版本號即成功。
- 下載地址Python官網

2. 安裝Flask

使用Python的包管理工具pip安裝Flask:

pip install flask

驗證安裝:打開Python交互環境(pythonpython3),輸入 import flask 無報錯即成功。

三、項目開發流程

1. 創建虛擬環境(必做!)

爲避免不同項目依賴衝突,建議爲每個項目創建獨立的虛擬環境:
- 創建虛擬環境(Python 3.3+內置venv模塊):

  python -m venv myflaskenv  # Windows/Linux/Mac
  • 激活虛擬環境
  • Windows(命令提示符):myflaskenv\Scripts\activate
  • Linux/Mac(終端):source myflaskenv/bin/activate
    激活後終端前綴會顯示(myflaskenv),表示環境生效。

2. 初始化項目結構

良好的項目結構能讓代碼更易維護。建議基礎結構如下:

myflaskapp/          # 項目根目錄
├── app.py           # 應用入口
├── requirements.txt # 依賴清單(生成命令:pip freeze > requirements.txt)
├── static/          # 靜態文件(CSS/JS/圖片)
│   └── css/
│       └── style.css
└── templates/       # HTML模板
    └── index.html

3. 第一個“Hello World”

app.py中編寫基礎代碼:

from flask import Flask  # 導入Flask類

app = Flask(__name__)    # 創建應用實例(__name__表示當前模塊)

@app.route('/')          # 定義路由:訪問根路徑時執行下方函數
def index():             # 視圖函數:處理請求並返回響應
    return "Hello, Flask!"  # 返回字符串

if __name__ == '__main__':  # 當直接運行app.py時執行
    app.run(debug=True)     # 啓動開發服務器(debug=True時代碼修改自動重啓)

運行應用:

python app.py

打開瀏覽器訪問 http://127.0.0.1:5000/,即可看到“Hello, Flask!”。

4. 路由與動態參數

基礎路由

除了根路徑/,還可定義其他路徑:

@app.route('/about')
def about():
    return "關於我們的項目"

@app.route('/user')
def user_profile():
    return "用戶資料頁"

動態路由參數

如需從URL獲取參數(如用戶ID),使用<參數名>語法:

@app.route('/user/<username>')  # URL中<username>會作爲參數傳入函數
def show_user(username):
    return f"用戶:{username}"  # 直接渲染參數

@app.route('/post/<int:post_id>')  # <int:post_id>限制參數爲整數
def show_post(post_id):
    return f"文章ID:{post_id}"

5. 模板系統(渲染HTML)

Flask默認使用Jinja2模板引擎,需在templates文件夾中編寫HTML文件:

templates/index.html

<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>  <!-- 變量渲染 -->
</head>
<body>
    <h1>{{ message }}</h1>
    {% if is_logged_in %}  <!-- 條件判斷 -->
        <p>歡迎回來!</p>
    {% else %}
        <p>請先登錄</p>
    {% endif %}
    <ul>
        {% for item in items %}  <!-- 循環遍歷 -->
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
</body>
</html>

app.py中渲染模板:

from flask import render_template  # 導入模板渲染函數

@app.route('/page')
def page():
    data = {
        'title': '首頁',
        'message': '歡迎使用Flask模板',
        'is_logged_in': True,
        'items': ['項目1', '項目2', '項目3']
    }
    return render_template('index.html', **data)  # 傳遞數據到模板

靜態文件引用:在模板中通過url_for('static', filename='路徑')引用CSS/JS/圖片:

<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">

6. 處理表單與數據

獲取表單數據

使用request對象獲取用戶輸入(需先導入):

from flask import request, render_template, redirect, url_for

@app.route('/login', methods=['GET', 'POST'])  # 允許GET(顯示錶單)和POST(提交數據)
def login():
    if request.method == 'POST':  # 判斷請求方法
        username = request.form.get('username')  # 獲取表單中的username字段
        password = request.form.get('password')
        if username == 'admin' and password == '123456':
            return redirect(url_for('dashboard'))  # 跳轉到dashboard頁面
        else:
            return "用戶名或密碼錯誤"
    return render_template('login.html')  # GET請求時顯示錶單

簡單表單驗證

可使用flask.flash反饋操作結果(如登錄失敗提示):

from flask import flash

@app.route('/login', methods=['POST'])
def login_post():
    if not request.form.get('username'):
        flash('用戶名不能爲空', 'error')  # 錯誤消息
        return redirect(url_for('login'))
    # ... 其他驗證邏輯

在模板中顯示flash消息:

{% with messages = get_flashed_messages(with_categories=true) %}
    {% if messages %}
        {% for category, message in messages %}
            <div class="{{ category }}">{{ message }}</div>
        {% endfor %}
    {% endif %}
{% endwith %}

7. 數據庫操作(Flask-SQLAlchemy)

Flask本身不包含數據庫功能,需藉助擴展。以SQLite(輕量無需配置)爲例:

安裝依賴

pip install flask-sqlalchemy  # ORM工具,簡化數據庫操作

初始化數據庫

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb.db'  # SQLite數據庫路徑
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 關閉修改跟蹤(節省資源)
db = SQLAlchemy(app)  # 初始化ORM對象

定義數據模型

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)  # 主鍵
    username = db.Column(db.String(80), unique=True, nullable=False)  # 用戶名
    email = db.Column(db.String(120), unique=True, nullable=False)  # 郵箱

    def __repr__(self):
        return f'<User {self.username}>'

創建表與增刪改查

在終端執行以下命令創建表(需進入Python交互環境):

from app import app, db, User

with app.app_context():  # 應用上下文(避免運行時錯誤)
    db.create_all()  # 根據模型創建所有表

    # 添加用戶
    user = User(username='test', email='test@example.com')
    db.session.add(user)
    db.session.commit()  # 提交事務

    # 查詢用戶
    users = User.query.all()  # 查詢所有用戶
    user = User.query.filter_by(username='test').first()  # 查詢單個用戶

    # 刪除用戶
    db.session.delete(user)
    db.session.commit()

四、項目最佳實踐

1. 配置管理

避免硬編碼配置,通過環境變量或config.py分離配置:

方法1:環境變量

import os
from dotenv import load_dotenv  # 需安裝:pip install python-dotenv

load_dotenv()  # 讀取.env文件
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')  # 從環境變量獲取密鑰
app.config['DATABASE_URI'] = os.getenv('DATABASE_URI', 'sqlite:///default.db')  # 默認值

.env文件(根目錄下):

SECRET_KEY=your_secret_key_here
FLASK_ENV=development

方法2:多環境配置
創建config.py

class Config:
    SECRET_KEY = 'your_secret_key'

class DevelopmentConfig(Config):
    DEBUG = True
    DATABASE_URI = 'sqlite:///dev.db'

class ProductionConfig(Config):
    DEBUG = False
    DATABASE_URI = os.getenv('DATABASE_URI')

使用時根據環境加載配置:

app.config.from_object(DevelopmentConfig)  # 開發環境
# app.config.from_object(ProductionConfig)  # 生產環境

2. 代碼結構與藍圖

當項目較大時,需拆分功能模塊(如用戶模塊、訂單模塊),用藍圖(Blueprint) 實現:

創建藍圖(如users.py

from flask import Blueprint, render_template

users_bp = Blueprint('users', __name__, url_prefix='/users')  # 路由前綴

@users_bp.route('/profile')
def profile():
    return render_template('users/profile.html')

註冊藍圖(在app.py中)

from users import users_bp
app.register_blueprint(users_bp)  # 註冊藍圖

使用藍圖後,訪問路徑變爲/users/profile

3. 錯誤處理

自定義404/500頁面,提升用戶體驗:

@app.errorhandler(404)
def not_found(e):
    return render_template('404.html'), 404  # 返回狀態碼404

@app.errorhandler(500)
def server_error(e):
    return render_template('500.html'), 500

4. 日誌記錄

記錄關鍵操作(如登錄、錯誤)便於調試:

import logging
from logging.handlers import RotatingFileHandler

def setup_logging(app):
    file_handler = RotatingFileHandler('app.log', maxBytes=10240, backupCount=10)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
    ))
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
    app.logger.info('Flask應用啓動')

# 在app初始化後調用
setup_logging(app)

5. 測試

pytest或Flask測試客戶端驗證功能:

# 安裝pytest: pip install pytest
# test_app.py
import pytest
from app import app, db

@pytest.fixture
def client():
    app.config['TESTING'] = True
    with app.test_client() as client:  # 測試客戶端
        with app.app_context():
            db.create_all()
            yield client
            db.drop_all()  # 測試後刪除表

def test_login(client):
    response = client.post('/login', data={'username': 'admin', 'password': '123'}, follow_redirects=True)
    assert response.status_code == 200  # 斷言登錄成功(跳轉到dashboard)

五、部署簡介

開發完成後,需部署到服務器讓他人訪問:

1. 本地部署

  • 生產環境關閉debugapp.run(debug=False)
  • 使用gunicorn作爲WSGI服務器(比Flask自帶服務器更穩定):
  pip install gunicorn
  gunicorn -w 4 -b 0.0.0.0:8000 app:app  # 4個工作進程,綁定8000端口

2. 雲平臺部署

  • PythonAnywhere:適合新手,直接上傳代碼+配置虛擬環境。
  • Heroku:需準備Procfile文件:
  web: gunicorn app:app

並配置環境變量(heroku config:set SECRET_KEY=xxx)。

六、總結

Flask的核心是“輕量靈活”,從“Hello World”到完整項目,需掌握:
1. 路由與視圖函數基礎
2. 模板與靜態文件管理
3. 表單處理與數據驗證
4. 數據庫操作(SQLAlchemy)
5. 項目結構(藍圖、配置、日誌)

通過實踐(如開發一個簡單博客、待辦事項應用)鞏固知識,逐步提升項目複雜度。Flask的擴展性強,後續可結合Celery(異步任務)、Flask-RESTful(API開發)等擴展,滿足更復雜需求。

最後:動手編碼是學習的最佳方式,從模仿到獨立開發,你會逐步掌握Web開發的核心邏輯!

小夜