日前我們有介紹Python – (2) 使用Python+Flask撰寫API
這篇來說說,如何用簡單的幾行程式就可以撰寫網頁,並Submit資料
要達到的情境如下:
1. 網頁顯示textbox,供使用者填寫名稱
2. 網頁按下submit
3. 回傳 “Hello, " + 使用者名稱
✦ 撰寫demo.py
#!flask/bin/python from flask import Flask, request, render_template #記得要import render_template app = Flask(__name__) #網頁執行/say_hello時,會導至index.html @app.route('/say_hello', methods=['GET']) def getdata(): return render_template('index.html') #index.html按下submit時,會取得前端傳來的username,並回傳"Hello, World! "+name @app.route('/say_hello', methods=['POST']) def submit(): name = request.form.get('username') return "Hello, "+name if __name__ == '__main__': app.run(debug=True)
✦ 在demo.py的路徑下,新增一個資料夾,名為templates (只能命名為templates,命名為其他名稱flask會找不到)
✦ 在templates資料夾下,新增一個index.html
✦ index.html內容如下
<!doctype html> <title>Hello, World!</title> <h1>Hello, your name is ?</h1> <p></p> <form action="/say_hello" method="post"> <label>Name:</label> <input type="textbox" name="username"> <input type="submit" value="Submit"> </form>
✦ 瀏覽器輸入http://127.0.0.1/say_hello
✦ textbox輸入名稱
✦ 按下submit,就會回傳"Hello, " + username
請問 我為甚麼會出現 找不到網頁?
讚讚
請問你的網址是打什麼呢?
讚讚
請問 可以傳int型態的資料到網頁裡嗎?
讚讚
可用:userid = request.form.get(‘userid’, type=int)
讚讚