การใช้ ฟังก์ชั่น url_for() ใช้สำหรับการ route ไปยังฟังก์ชั่นที่อยู่ในโปรแกรม ของ Flask

แชร์ความรู้ภาษา Python ไพทอน การเขียนโปรแกรมภาษาไพทอน

Moderator: mindphp, ผู้ดูแลกระดาน

ภาพประจำตัวสมาชิก
jirawoot
PHP VIP Members
PHP VIP Members
โพสต์: 3129
ลงทะเบียนเมื่อ: 17/06/2019 10:30 am

การใช้ ฟังก์ชั่น url_for() ใช้สำหรับการ route ไปยังฟังก์ชั่นที่อยู่ในโปรแกรม ของ Flask

โพสต์ที่ยังไม่ได้อ่าน โดย jirawoot »

การใช้ ฟังก์ชั่น url_for() ของ Flask
ในภาษา Python นั้นมี flask เป็นตัวที่ใช้สำหรับการสร้างเว็บไซต์ ซึ่งสามารถใช้จัดการหน้าเว็บไซต์ และในตัว flask นั้นก็จะมีตัวฟังก์ชั่นที่มาชื่อ url_for ใช้สำหรับการ route ไปยังฟังก์ชั่นที่อยู่ในโค้ดโปรแกรมของเรา ฟังก์ชั่นจะคล้ายๆ กับฟังก์ชั่น render_template มาตัวอย่างดังนี้

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

from flask import Flask,url_for ,redirect
app=Flask(__name__)
@app.route('/')
def index():
    return redirect(url_for('test2'))
@app.route('/test2')
def test():
    return "Hello test"
@app.route('/test3')
def test2():
    return "Hello test2"
if __name__=='__main__':
    app.run()
จากตัวอย่างด้านบนเป็นการ redirect ยังฟังก์ชั่นที่อยู่ route /test3 ผลลัพธ์จะได้ดังตัวอย่างด้านล่าง
Selection_054.png
Selection_054.png (4.69 KiB) Viewed 1176 times
อีกตัวอย่างหนึ่งใช้จากหน้า html

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a class="btn" href="{{url_for('test')}}">test</a><br>
<a class="btn" href="{{url_for('test2')}}">test2</a>
</body>
</html>
Selection_055.png
Selection_055.png (3.87 KiB) Viewed 1176 times
โค้ด Python

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

from flask import Flask,render_template
app=Flask(__name__)
@app.route('/')
def index():
    return render_template('home.html')
@app.route('/test2')
def test():
    return "Hello test"
@app.route('/test3')
def test2():
    return "Hello test2"
if __name__=='__main__':
    app.run()
จะได้ผลลัพธ์ดังรูป
ถ้าเราคลิกที่ลิ้ง test
Selection_056.png
Selection_056.png (4.4 KiB) Viewed 1176 times
คลิกที่ลิ้ง test2
Selection_057.png
Selection_057.png (4.64 KiB) Viewed 1176 times
อ้างอิง
http://flask.pocoo.org/docs/1.0/api/
https://www.stackoverflow.com/questions/7478366/create-dynamic-urls-in-flask-with-url-for
http://screenth.blogspot.com/2017/07/flask-hello-world.html
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 63