1. 安裝環境
打開命令列(Terminal 或 CMD),輸入:pip install Flask
安裝好後,用以下指令確認:pip show flask
2. 建立第一個 Flask 網站
在你的資料夾裡,建立一個檔案 app.py,內容如下:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, Flask!'
if __name__ == '__main__':
app.run(debug=True)
然後在 Terminal 執行:python app.py
看到訊息:Running on http://127.0.0.1:5000/
打開瀏覽器輸入 http://127.0.0.1:5000/,就會看到網頁顯示 Hello, Flask!
3. 理解路由 (Route)
新增一個頁面 /about:
@app.route('/about')
def about():
return '這是 About 頁面'
訪問 http://127.0.0.1:5000/about,看到「這是 About 頁面」。
✅ 小結:
- 每個
@app.route('網址')就是對應一個網頁入口。 def 函式名稱():決定網址回傳的內容。
4. 回傳 HTML 頁面
新增資料夾 templates,並建立 index.html:
<!DOCTYPE html>
<html>
<head>
<title>Flask Demo</title>
</head>
<body>
<h1>歡迎來到 Flask 網站!</h1>
<p>這是第一個 HTML 頁面</p>
</body>
</html>
修改 app.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
重新整理 http://127.0.0.1:5000/,就能看到漂亮的 HTML 頁面。
5. 接收表單 (Form) 資料
在 templates 資料夾新增 form.html:
<!DOCTYPE html>
<html>
<head>
<title>Flask 表單</title>
</head>
<body>
<h1>輸入你的名字</h1>
<form action="/greet" method="post">
<input type="text" name="username" placeholder="你的名字">
<button type="submit">送出</button>
</form>
</body>
</html>
修改 app.py:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
return render_template('form.html')
@app.route('/greet', methods=['POST'])
def greet():
username = request.form['username']
return f'Hello, {username}!歡迎使用 Flask!'
if __name__ == '__main__':
app.run(debug=True)
流程說明:
- 使用者在首頁輸入名字。
- 按送出後,傳到
/greet。 greet()讀取表單資料並顯示打招呼的文字。
🔥 Bonus:目錄結構範例
建議的資料夾結構:
/你的專案
app.py
/templates
index.html
form.html
/static
(放 CSS、JS、圖片)
如果想加上 CSS、JS,可以放到 /static 裡!
請先 登入 以發表留言。