Python Flask入门教程 – wiki基地

我再次抱歉。看來我一直錯誤地使用了工具名稱。我目前沒有直接寫入文件或執行 shell 命令的工具。

這意味著我無法在您的文件系統上直接創建 app.pytemplates 目錄、static 目錄以及它們內部的文件。

但是,我仍然可以提供您所需的 Python Flask 入門教程的內容。我將以 Markdown 格式呈現教程文章,並在其中包含每個文件的代碼內容,您可以手動創建這些文件並將代碼複製貼上。


Python Flask 入門教程

Flask 是一個輕量級的 Python Web 框架,它被稱為「微框架」,因為它不包含 ORM(對象關係映射器)或類似的功能。它提供構建 Web 應用程序所需的核心功能,並允許開發人員自由選擇其他組件。

1. 為什麼選擇 Flask?

  • 輕量級且靈活: Flask 的核心很小,但高度可擴展。你可以根據項目需求選擇添加任何庫。
  • 易於學習和使用: 對於初學者來說,Flask 的 API 簡單直觀,上手快。
  • 強大的社群和豐富的擴展: 雖然核心精簡,但 Flask 擁有龐大的社群和許多第三方擴展,可以輕鬆添加數據庫集成、表單驗證、用戶認證等功能。
  • 良好的文檔: Flask 的官方文檔非常清晰和全面。

2. 環境準備與安裝

在開始之前,請確保你的系統上安裝了 Python 3。建議使用虛擬環境來管理項目依賴。

  1. 創建並激活虛擬環境:

    在終端中執行以下命令:

    “`bash
    python3 -m venv venv

    在 macOS/Linux 上

    source venv/bin/activate

    在 Windows 上

    venv\Scripts\activate
    “`

  2. 安裝 Flask:

    激活虛擬環境後,執行:

    bash
    pip install Flask

3. 你的第一個 Flask 應用程序 (Hello, World!)

讓我們創建一個最簡單的 Flask 應用程序。

請手動創建一個名為 app.py 的文件,並將以下內容複製貼上到其中:

“`python
from flask import Flask

創建一個 Flask 應用實例

app = Flask(name)

定義一個路由 (URL 路徑)

@app.route(‘/’)
def hello_world():
return ‘Hello, World!’

運行應用程序

if name == ‘main‘:
app.run(debug=True)
“`

運行應用程序:

在終端中,確保你已激活虛擬環境,然後運行:

bash
python app.py

你將看到類似以下的輸出:

* Serving Flask app 'app'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: XXX-XXX-XXX

打開你的瀏覽器,訪問 http://127.0.0.1:5000/,你將看到 “Hello, World!”。

  • Flask(__name__): 創建一個 Flask 應用實例。__name__ 是一個特殊的 Python 變量,它會被設置為當前模塊的名稱。Flask 用它來確定應用程序的根路徑,以便找到資源文件(如模板和靜態文件)。
  • @app.route('/'): 這是一個裝飾器,它將 hello_world 函數綁定到 URL 路徑 /。當用戶訪問根 URL 時,hello_world 函數將被執行。
  • app.run(debug=True): 啟動 Flask 開發服務器。debug=True 會啟用調試模式,這在開發過程中非常有用,因為它會在代碼更改時自動重載服務器,並提供一個交互式調試器。

4. 路由 (Routing)

路由是將 URL 映射到應用程序中的視圖函數的方式。

修改 app.py,將其內容替換為以下代碼,以添加更多路由:

“`python
from flask import Flask

app = Flask(name)

@app.route(‘/’)
def hello_world():
return ‘Hello, World!’

@app.route(‘/about’)
def about():
return ‘這是一個關於頁面。’

@app.route(‘/user/‘)
def show_user_profile(username):
# show the user profile for that user
return f’用戶: {username}’

@app.route(‘/post/‘)
def show_post(post_id):
# show the post with the given id, the id is an integer
return f’文章 ID: {post_id}’

if name == ‘main‘:
app.run(debug=True)
“`

現在,你可以訪問:
* http://127.0.0.1:5000/
* http://127.0.0.1:5000/about
* http://127.0.0.1:5000/user/Alice
* http://127.0.0.1:5000/post/123

Flask 路由支持變量規則,你可以指定變量的類型(如 <int:post_id>)。

5. 模板 (Templates)

直接在 Python 代碼中返回 HTML 字符串很快就會變得難以管理。Flask 使用 Jinja2 作為其模板引擎,允許你將 HTML 結構與 Python 邏輯分離。

  1. 創建 templates 目錄:
    在與 app.py 同級的目錄下,手動創建一個名為 templates 的文件夾。Flask 會自動在這個文件夾中查找模板文件。

  2. 創建模板文件:

    請在 templates 目錄下創建一個名為 index.html 的文件,並將以下內容複製貼上到其中:

    html
    <!DOCTYPE html>
    <html lang="zh-Hant">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    </head>
    <body>
    <h1>歡迎來到 {{ name }} 的網站!</h1>
    <p>這是一個使用 Flask 和 Jinja2 模板的範例。</p>
    <a href="/about">關於我們</a>
    </body>
    </html>

    請在 templates 目錄下創建一個名為 about.html 的文件,並將以下內容複製貼上到其中:

    html
    <!DOCTYPE html>
    <html lang="zh-Hant">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>關於我們</title>
    </head>
    <body>
    <h1>關於我們</h1>
    <p>我們致力於提供最好的服務。</p>
    <a href="/">回首頁</a>
    </body>
    </html>

  3. 修改 app.py 以渲染模板:

    app.py 的內容替換為以下代碼:

    “`python
    from flask import Flask, render_template

    app = Flask(name)

    @app.route(‘/’)
    def index():
    return render_template(‘index.html’, name=’我的 Flask 應用’, title=’首頁’)

    @app.route(‘/about’)
    def about():
    return render_template(‘about.html’)

    if name == ‘main‘:
    app.run(debug=True)
    “`

  4. render_template(): 這個函數用於渲染模板。第一個參數是模板文件的名稱,後續的關鍵字參數會作為變量傳遞給模板。

  5. {{ variable }}: 在 Jinja2 模板中,雙大括號用於顯示從 Flask 傳遞過來的變量。

現在重啟應用程序並訪問 http://127.0.0.1:5000/http://127.0.0.1:5000/about,你將看到渲染後的 HTML 頁面。

6. 靜態文件 (Static Files)

靜態文件包括 CSS 樣式表、JavaScript 文件和圖片等。Flask 會在應用程序的 static 目錄中查找這些文件。

  1. 創建 static 目錄:
    在與 app.py 同級的目錄下,手動創建一個名為 static 的文件夾。

  2. 創建 CSS 文件:

    請在 static 目錄下創建一個名為 style.css 的文件,並將以下內容複製貼上到其中:

    css
    body {
    font-family: Arial, sans-serif;
    margin: 20px;
    background-color: #f4f4f4;
    color: #333;
    }
    h1 {
    color: #0056b3;
    }
    p {
    line-height: 1.6;
    }
    a {
    color: #007bff;
    text-decoration: none;
    }
    a:hover {
    text-decoration: underline;
    }

  3. 修改 templates/index.html 以鏈接 CSS 文件:

    templates/index.html 的內容替換為以下代碼:

    html
    <!DOCTYPE html>
    <html lang="zh-Hant">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    </head>
    <body>
    <h1>歡迎來到 {{ name }} 的網站!</h1>
    <p>這是一個使用 Flask 和 Jinja2 模板的範例。</p>
    <a href="/about">關於我們</a>
    </body>
    </html>

  4. url_for('static', filename='style.css'): 這是 Flask 提供的一個函數,用於為靜態文件生成 URL。它會自動找到 static 目錄下的 style.css 文件。

重啟應用程序並訪問 http://127.0.0.1:5000/,你會看到頁面應用了新的樣式。

7. 表單 (Forms)

處理用戶輸入是 Web 應用程序的核心功能之一。Flask 提供了 request 對象來訪問傳入的請求數據。

  1. 修改 templates/index.html 添加一個簡單的表單:

    templates/index.html 的內容替換為以下代碼:

    “`html
    <!DOCTYPE html>




    {{ title }}

    歡迎來到 {{ name }} 的網站!

    這是一個使用 Flask 和 Jinja2 模板的範例。

    關於我們

    <h2>提交你的名字</h2>
    <form method="POST" action="/">
        <label for="username">名字:</label>
        <input type="text" id="username" name="username" required>
        <button type="submit">提交</button>
    </form>
    
    {% if submitted_name %}
        <p>你好,{{ submitted_name }}!</p>
    {% endif %}
    



    “`

  2. 修改 app.py 以處理表單提交:

    app.py 的內容替換為以下代碼:

    “`python
    from flask import Flask, render_template, request

    app = Flask(name)

    @app.route(‘/’, methods=[‘GET’, ‘POST’])
    def index():
    submitted_name = None
    if request.method == ‘POST’:
    submitted_name = request.form[‘username’]
    return render_template(‘index.html’, name=’我的 Flask 應用’, title=’首頁’, submitted_name=submitted_name)

    @app.route(‘/about’)
    def about():
    return render_template(‘about.html’)

    @app.route(‘/user/‘)
    def show_user_profile(username):
    # show the user profile for that user
    return f’用戶: {username}’

    @app.route(‘/post/‘)
    def show_post(post_id):
    # show the post with the given id, the id is an integer
    return f’文章 ID: {post_id}’

    if name == ‘main‘:
    app.run(debug=True)
    “`

  3. methods=['GET', 'POST']: 在路由裝飾器中指定該路由可以處理 GET 和 POST 請求。

  4. request.method == 'POST': 檢查請求方法是否為 POST,這表示表單已被提交。
  5. request.form['username']: 從提交的表單數據中獲取名為 username 的字段值。
  6. {% if submitted_name %}: Jinja2 模板中的條件語句,用於根據變量是否存在來顯示內容。

現在,訪問 http://127.0.0.1:5000/,輸入你的名字並提交,你會看到頁面上顯示問候語。

8. 數據庫集成 (簡要)

Flask 本身不包含數據庫抽象層,但你可以輕鬆地與各種數據庫集成。最常見的選擇是使用 SQLAlchemy(一個強大的 ORM)配合 Flask-SQLAlchemy 擴展。

安裝 Flask-SQLAlchemy:

bash
pip install Flask-SQLAlchemy

基本用法示例 (不包含在主 app.py 中,僅作概念說明):

“`python

from flask import Flask

from flask_sqlalchemy import SQLAlchemy

app = Flask(name)

app.config[‘SQLALCHEMY_DATABASE_URI’] = ‘sqlite:///site.db’ # 使用 SQLite 數據庫

db = SQLAlchemy(app)

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’

# 在應用上下文中創建數據庫表 (首次運行時)

# with app.app_context():

# db.create_all()

# 示例:添加一個新用戶

# with app.app_context():

# new_user = User(username=’testuser’, email=’[email protected]’)

# db.session.add(new_user)

# db.session.commit()

# 示例:查詢所有用戶

# with app.app_context():

# users = User.query.all()

# for user in users:

# print(user.username)

“`

9. 部署 (簡要)

Flask 開發服務器不適用於生產環境。在生產環境中,你需要使用一個 WSGI 服務器(如 Gunicorn 或 uWSGI)來運行你的 Flask 應用程序,並通常會配合一個反向代理服務器(如 Nginx)。

部署流程概述:

  1. 安裝 WSGI 服務器: pip install gunicorn
  2. 運行應用程序 (例如使用 Gunicorn): gunicorn -w 4 app:app (其中 app:app 表示 app.py 文件中的 app 實例)
  3. 配置反向代理: 配置 Nginx 或 Apache 將請求轉發到 WSGI 服務器。
  4. 使用 Supervisor 或 Systemd 管理進程: 確保應用程序在後台運行並在崩潰時自動重啟。

總結

這個教程涵蓋了 Flask 的基本概念,包括:

  • 安裝和設置虛擬環境
  • 創建一個基本的 Flask 應用程序
  • 定義路由和處理 URL 變量
  • 使用 Jinja2 模板渲染 HTML
  • 管理靜態文件(CSS)
  • 處理表單提交
  • 簡要介紹數據庫集成和部署

Flask 是一個功能強大且靈活的框架,非常適合構建從小型 API 到複雜 Web 應用程序的各種項目。繼續探索 Flask 的官方文檔和各種擴展,你將能夠構建出色的應用程序。

滚动至顶部