15 กรกฎาคม 2560

Flask : เริ่มต้นกับ hello world

เมื่อติดตั้ง virtualenv และ flask เรียบร้อยแล้ว เริ่ม dev งานแรก
* อย่าลืมเรียกใช้ virtual environment => source venv/bin/activate
** ทดสอบบน Google App Engine จำเป็นต้องใช้งาน port 8080

1. ไปยัง directory ที่เราสร้างไว้ แล้วสร้างไฟล์ app.py  ref.
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
   return 'Hello World’

if __name__ == '__main__':
  app.run(host='127.0.0.1', port=8080,debug=True)

ทดสอบ run
python app.py

ตัวอย่าง output
(py3) yuunai_th@yuunai-app:~/test2$ python app.py
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 130-808-004
127.0.0.1 - - [15/Jul/2017 12:51:28] "GET /?authuser=1 HTTP/1.0" 200 -

กดที่ ไอคอน ซ้ายสุด เลือก preview on port 8080 เพื่อตรวจสอบโปรแกรม


2. ปรับแต่ง app.py

@app.route() 

เป็นตัวกำหนด path ที่ URL ว่าจะให้ไปเรียกใช้ function อะไร โดยวางบรรทัดก่อน function นั้น

เราสามารถ ส่งผ่าน variable มาจาก URL ได้ เช่น
@app.route('/hello/<string:name>')
def Home(name):
    return ("<h1>Hello %s!! </h1>" % name)

<string:name> string คือ conversion variable เพื่อให้อยู่ใน type ที่ต้องการ

url_for('function',parameter = value)

ใช้สำหรับ redirect ไปเรียกใช้งาน function ที่เคยประกาศไว้แล้ว เหมาะสำหรับ dynamic web page

return redirect(url_for('hello_guest',guest = name))

HTTP method จาก app.route()
ใช้เป็นตัวรับ method ว่าจะให้ response แบบไหน
login.html
<html>
   <body>
      
      <form action = "http://localhost:5000/login" method = "post">
         <p>Enter Name:</p>
         <p><input type = "text" name = "nm" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
      
   </body>
</html>
from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/success/<name>')
def success(name):
   return 'welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      user = request.form['nm']
      return redirect(url_for('success',name = user))
   else:
      user = request.args.get('nm')
      return redirect(url_for('success',name = user))

if __name__ == '__main__':
   app.run(debug = True)

เมื่อ login.html sumit form ส่งมายัง /login , app.route จะเช็กว่าเป็น method อะไรจาก
request.method 

จากตัวอย่างจะเห็นว่า ในการอ่านค่า variable

POST ใช้ request.form['nm'] 
GET ใช้ request.args.get('nm') 






ไม่มีความคิดเห็น:

แสดงความคิดเห็น