Flask ใช้ Jinja เป็น HTML templates
Install Flask
สร้าง folder สำหรับโปรเจ็กส์
> mkdir myproject ; cd myproject
สร้างไฟล์ requirements.txt
Flask==2.0.2
พิมพ์คำสั่งตามนี้
python -m venv venv .\venv\scripts\activate pip install -r requirements.txt
สร้างไฟล์ app.py หรือชื่ออื่นก็ได้ เช่น hello.py แต่ห้ามชื่อ flask.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
ไฟล์ชื่อ app.py สั่งรัน Flask แบบนี้
flask run
แต่ถ้าไฟล์ชื่ออื่น เช่น ไฟล์ชื่อ hello.py สั่งรันแบบนี้
flask --app hello run
รันแบบ debug – restarts the server whenever you make changes to the code.
flask run --debug
เปิด browser ไปที่ http://127.0.0.1:5000/

HTML Escaping
from flask import Flask
from markupsafe import escape
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
@app.route("/<name>")
def hello(name):
return f"Hello, {escape(name)}!"
ไปที่ http://127.0.0.1:5000/jack
จะได้ Hello, jack!
Routing
from flask import Flask
from markupsafe import escape
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello_world():
return 'Hello, World'
@app.route("/<name>")
def hello(name):
return f"Hello, {escape(name)}!"
Variable Rules
from flask import Flask
from markupsafe import escape
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello_world():
return 'Hello, World'
@app.route("/<name>")
def hello(name):
return f"Hello, {escape(name)}!"
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return f'User {escape(username)}'
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return f'Post {post_id}'
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return f'Subpath {escape(subpath)}'
Converter types:
string | (default) accepts any text without a slash |
int | accepts positive integers |
float | accepts positive floating point values |
path | like string but also accepts slashes |
uuid | accepts UUID strings |