# Flask 入門 參考內容: * https://medium.com/@charming_rust_oyster_221/%E4%BD%BF%E7%94%A8-flask-%E5%89%B5%E5%BB%BA-web-api-%E7%AD%86%E8%A8%98-b5618543632e * https://medium.com/datainpoint/flask-web-api-quickstart-3b13d96cccc2 * https://hackmd.io/@shaoeChen/HJiZtEngG/https%3A%2F%2Fhackmd.io%2Fs%2FSyP4YEnef * https://segmentfault.com/a/1190000017330435 * https://ithelp.ithome.com.tw/articles/10224586 * https://medium.com/seaniap/python-web-flask-%E4%BD%BF%E7%94%A8sqlalchemy%E8%B3%87%E6%96%99%E5%BA%AB-8fc49c584ddb ## API 程式碼與作業系統、與其他段程式碼彼此之間溝通的管道 ## 使用 Web API 的時機 具備下列特性時,使用 Web API 分享就顯得比使用文字格式資料集提供下載來得更好 * 資料更新的速度快、頻率高,生成靜態資料集檔案過於緩慢 * 使用者可能只需要龐大資料中的一個子集(subset) * 資料具備重複運算的特性(例如 rolling stats) ## Flask API 使用python撰寫輕量web應用框架 ## hello world 練習 ``` from flask import Flask app = Flask(__name__) #創建Flask對象,將使用該對象進行應用的配置和執行 @app.route('/') def hello_world(): return 'Hello, World!' if __name__ =="__main__": app.run(debug=True,port=8080) ``` 執行後打開瀏覽器就可看到結果 ## 使用HTML模板 模板文件路徑 Apps folder /app.py templates |-/index.html 用模板的時候,會返回render_template()的結果,下列程式會回傳index.html模板的渲染結果 app.py ``` from flask import Flask, render_template app = Flask(__name__) @app.route('/hello') def hello(): return render_template('index.html', name="Alex") if __name__ == '__main__': app.run(debug = True) ``` index.html 模板index.html依賴於app.py中的name ``` <html> <body> {% if name %} <h2>Hello {{ name }}.</h2> {% else %} <h2>Hello.</h2> {% endif %} </body> </html> ``` 執行後打開瀏覽器就可在 http://127.0.0.1:5000/hello 看到結果