20220929 My First Web App
學習目標:
- Visual Studio Code 基本操作
- 在本地端建立 Web App
- 學習建立 function
- 學習基本命令: if, print
Part 1: 建置新的工作區域(workspace repository)
步驟1: 電腦建立一個新的資料夾, 例如, pythonlab_111_MIG004301
步驟2: 打開 Visual Studio Code 並點選 File -> Open Folder… -> pythonlab_111_MIG004301, 並點選"Select Folder"
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 →
步驟3: 信任作者
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 →
步驟4: 新的 workspace, pythonlab_111_MIG004301
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 →
步驟5: 練習操作 workspace 的元件, 例如:
- New File…
- New Folder…
- Terminal
Part 2: Python Flask - 建立 Web App
步驟1: 打開 Visual Studio Code 並點選 workspace
步驟2: 建立一個新的專案, firstApp, 並建立該專案專屬的資料夾
步驟3: 打開 terminal 安裝 flask
如果無法執行 pip 的同學, 可以嘗試下列方法
步驟4: 如何驗證 flask 有安裝成功
[原步驟5-6 skip]
步驟7: 點選專案資料夾,firstApp,在專案的資料夾中新增檔案, 並取名為 app.py
(Ref: https://flask.palletsprojects.com/en/2.2.x/tutorial/layout/)
第3行: 建立一個 Flask 應用程式的物件, app. 傳入的參數, '_name_', 是 python 內建的變數, 它會儲存目前這個程式執行的模組名稱, 也就是目前這個程式在哪個模組下執行. 如果這個程式是當成主程式來執行, '_name_' 的值就是 _main_.
第7-8行: 是一個函式 (function)
第6行: 在 function 上面用一個 "@" 符號, 就是 function 的裝飾(decorator), 以function為基礎,提供附加的功能. 在這裡是 app.route 的功能.
第10行: 如果目前這個程式是以主程式來執行
第11行: 立刻啟動伺服器
步驟8: 執行應用程式
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 →
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 →
步驟9: 在啟動伺服器之前, 新增網站頁面.
第10行: 代表我們要處理的網站路徑
第11-12行: 執行 readme() 函式
參考資料:
- Flask 函式庫: https://flask.palletsprojects.com/en/2.2.x/tutorial/layout/
- Python print() function: https://www.w3schools.com/python/ref_func_print.asp
- Python functions: https://www.w3schools.com/python/python_functions.asp
- Python conditions: (if… else…) https://www.w3schools.com/python/python_conditions.asp
備註:
步驟5: 點選專案資料夾,firstApp,在專案的資料夾中新增檔案, 並取名為 app.py
(Ref: https://flask.palletsprojects.com/en/2.2.x/tutorial/layout/)
第3行: 建立一個 Flask 應用程式的物件, app. 傳入的參數, '_name_', 是 python 內建的變數, 它會儲存目前這個程式執行的模組名稱, 也就是目前這個程式在哪個模組下執行. 如果這個程式是當成主程式來執行, '_name_' 的值就是 _main_.
第7-8行: 是一個函式 (function)
第6行: 在 function 上面用一個 "@" 符號, 就是 function 的裝飾(decorator), 以function為基礎,提供附加的功能. 在這裡是 app.route 的功能.
步驟6: 執行應用程式
附註: 如果是使用 Mac 的同學,