การ GET ข้อมูลที่ส่งมากับ URL ในภาษา Python

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: การ GET ข้อมูลที่ส่งมากับ URL ในภาษา Python

การ GET ข้อมูลที่ส่งมากับ URL ในภาษา Python

โดย jirawoot » 05/07/2019 4:46 pm

การ GET ข้อมูลที่ส่งมากับ URL ในภาษา Python
ในภาษาPython มีวิธีการ GET ข้อมูลที่ถูกส่งมาพร้อมกับ URL โดยการเรียกใช้โมดูลของตัว flask ที่ฟังก์ชั่น request หลายๆคนอาจมองวิธีนี้อยู่ วันนี้ผมจึงของมาแชร์ความรู้นี้เพื่อประโยชน์และไว้ให้น้องๆได้ดูและศึกษา
อันนี้จะหน้าของโค้ด HTML
Selection_043.png
Selection_043.png (5.23 KiB) Viewed 3492 times

โค้ด: เลือกทั้งหมด

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="{{url_for('test')}}" method="GET">
    ชื่อ
    <input type="text" name="frist_name">
    นานสกุล
    <input type="text" name="last_name">
    <input type="submit" value="submit">
</form>
</body>
</html>
Selection_044.png
Selection_044.png (6.58 KiB) Viewed 3492 times
จากรูปภาพด้านบนจะเป็นการส่งข้อมูลด้วย metthod get โดยข้อมูลจะถูกส่งไปกับ url ตอนกด submit
Selection_045.png
Selection_045.png (4.44 KiB) Viewed 3492 times
แล้วเราก็ทำการดึงค่าตัวแปรจาก ลิ้ง URL มาเก็บไว้

โค้ด: เลือกทั้งหมด

from flask import Flask, render_template,request
app=Flask(__name__)
@app.route('/')
def index():
    return render_template('home.html')
@app.route('/test')
def test():
    frist_name=request.args.get('frist_name')
    last_name = request.args.get('last_name')
    return "Hello %s %s"%(frist_name,last_name)
if __name__=='__main__':
    app.run(debug=True)
แล้วทำการ return ค่าตัวแปรนั้นมาแสดงก็จะได้ดังรูปด้านล่างนี้
Selection_046.png
Selection_046.png (7.21 KiB) Viewed 3492 times


อ้างอิง
https://www.scotch.io/bar-talk/processing-incoming-request-data-in-flask
https://www.pythonise.com/feed/flask/the-flask-request-object
https://www.stackoverflow.com/questions/34671217/in-flask-what-is-request-args-and-how-is-it-used

ข้างบน