Try   HackMD

【第一篇】Flask 入門

tags: Flask教學

快速建立網站

官方網站:https://palletsprojects.com/p/flask/

首先,使用 Flask 必須要安裝程式庫,在終端機輸入以下指令以安裝 Flask(建議安裝在虛擬環境 virtualenv)。

$ pip install flask

建立一個檔案,命名為 app.py(請注意不要命名成 flask.py),輸入以下程式碼:

from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return "hello world" if __name__ == '__main__': app.run()

並在終端機執行(記得切換到 app.py 檔案路徑):

$ python app.py

Flask 便會迅速建立在 localhost:5000,所以我們只要在你常用的瀏覽器輸入網址 localhost:5000,便可以看到我們的網站已經建立。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

更改顯示內容

回到 app.py,可以看到第 7 行的 return,其實就是網頁上顯示的內容,更改它就會改變網頁,你也可以直接輸入把 HTML 輸入在這,例如:

return "<h1>hello world</h1>"

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

字體已套用上 HTML h1 的格式。

URL 路徑

一般來說,一個網站上一定不會只有一個頁面,可能有首頁、登入、個人資料設定、文章內容 等, 所以我們可以透過 Flask 建立不同的 URL。一樣回到 app.py,可以加入以下程式來建立:

from flask import Flask app = Flask(__name__) @app.route('/') def index(): return "hello world" @app.route('/login') def login(): return "login page" if __name__ == '__main__': app.run()

第 5 行與第 9 行差別在括號裡面不同,也就是 URL 不同,底下的 def 就是連線到該網址時會執行的區塊,回傳不同的文字來區別連到不同網址。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

動態網址連結

但我們有時候會需要依使用者的輸入,來建立不同的網址。雖然你可以透過剛剛的方法,來建立不同的 URL。但如果這些規則差不多,我們可以透過變數來設置。
舉例來說,一個部落格的文章,可以透過不同的文章索引,來建立相對應的網址; 不同的使用者名稱,會連線到該使用者的設定頁面。

# 上略 @app.route('/home/<user>') def userpage(user): return "你正在使用者" + user + "的頁面" # 下略

網址為 localhost:5000/home/penny。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

變數規則預設型態是 string,但如果你很確定輸入的型態是整數或其他,可以特別指定。

# 上略 @app.route('/post/<int:post_id>') def show_post(post_id): # 以指定的 id 來顯示文章,且此 id 為整數型態 return 'Post %d' % post_id # 下略

可接受型態:

型態 說明
string (預設)接受不含斜線的任何文字
int 正整數
float 正小數點
path 跟 string 一樣,但可以接受斜線
uuid 型態為 uuid

HTTP requests

Flask 預設可接受的 request 是 GET,如果要做像是表單或登入,就必須要使用 POST:

@app.route('/login', methods=['GET', 'POST']) def login(): return "hello world"

下一篇:【第二篇】Flask templates 網頁樣板