一、理論
Flask是一個輕量級的web框架,靈活易用。提供構建web應用所需的核心工具。
Flask依賴python的兩個庫
?? ?Werkzeug:flask的底層庫,提供了WSGI接口、HTTP請求和響應處理、路由等核心功能。
?? ?Jinja2:模板引擎,用于動態生成HTML頁面。
二、實踐
?
1、第一個flask應用
[root@localhost ~]# pip config set global.index-url http://mirrors.aliyun.com/pypi/simple
Writing to /root/.config/pip/pip.conf
[root@localhost ~]# pip3 config set global.index-url http://mirrors.aliyun.com/pypi/simple
Writing to /root/.config/pip/pip.conf
[root@localhost ~]# pip3 config set install.trusted-host mirrors.aliyun.com
Writing to /root/.config/pip/pip.conf
[root@localhost ~]# pip3 install --upgrade pip[root@localhost ~]# pip install flask[root@localhost ~]# vim a.py
from flask import Flask# 創建Flask應用實例
app=Flask(__name__)# 定義路由和視圖函數
@app.route('/') # 用戶的訪問url為根時,flask會調用hello_world()函數。
def hello_world():return 'Hello,World!'# 啟動應用
if __name__ == '__main__': # 該行用于確認當前腳本是否是通過命令行直接運行的,而不是作為其他模塊或程序的一部分被導入的。app.run(host='0.0.0.0',port='5000',debug=True) # 啟動flask開發服務器,debug=true表示啟用調試模式,可在開發過程中自動重載應用,并在發生錯誤時顯示詳細信息。 host指定監聽的地址,這里監聽本機所有可用的地址,port指定監聽的端口。[root@localhost ~]# python3 a.py # 運行該服務。* Serving Flask app 'a'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on all addresses (0.0.0.0)* Running on http://127.0.0.1:5000* Running on http://192.168.10.101:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 112-870-242[root@localhost ~]# firewall-cmd --add-port=5000/tcp # 開放端口
success [root@localhost ~]# curl 192.168.10.101:5000
Hello,World![root@localhost ~]# # 這里會這樣顯示是因為return的末尾未加\n(換行),所以導致這樣顯示。(命令行中輸入完命令在末尾默認會加上換行,所以不會出現這種情況。)修改代碼from flask import Flask# 創建Flask應用實例
app=Flask(__name__)# 定義路由和視圖函數
@app.route('/')
def hello_world():return 'Hello,World!\n' # 加上換行符即可。# 啟動應用
if __name__ == '__main__':app.run(host='0.0.0.0',port='5000',debug=True)[root@localhost ~]# curl 192.168.10.101:5000
Hello,World!
[root@localhost ~]# c^C[root@localhost ~]# vim a.py
[root@localhost ~]# python3 a.py* Serving Flask app 'a'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on all addresses (0.0.0.0)* Running on http://127.0.0.1:5000* Running on http://192.168.10.101:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 112-870-242
192.168.10.101 - - [21/Apr/2025 09:08:50] "GET / HTTP/1.1" 200 -
192.168.10.101 - - [21/Apr/2025 09:08:53] "GET / HTTP/1.1" 200 -2、flask路由與視圖函數
flask通過裝飾器@app.route()來定義路由,而視圖函數則負責處理用戶的請求并返回響應。[root@localhost ~]# vim a.py
from flask import Flask# 創建Flask應用實例
app=Flask(__name__)# 定義路由和視圖函數
@app.route('/')
def hello_world():return 'Hello,World!\n'@app.route('/greet/<name>') # 這里定義了路徑ip/greet/<name> 如果輸入1,參數1會傳遞到下面的return中,會顯示hello,1.
def greet(name):return f'Hello,{name}!\n' # f是用于字符串格式化,將輸出結果顯示為字符串。# 啟動應用
if __name__ == '__main__':app.run(host='0.0.0.0',port='5000',debug=True)[root@localhost ~]# python3 a.py* Serving Flask app 'a'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on all addresses (0.0.0.0)* Running on http://127.0.0.1:5000* Running on http://192.168.10.101:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 112-870-242
192.168.10.101 - - [21/Apr/2025 09:14:38] "GET /greet/1 HTTP/1.1" 200 -[root@localhost ~]# curl 192.168.10.101:5000/greet/1
Hello,1!注意,這里只能這樣寫,寫為192.168.10.101/greet/1:5000會失敗,它會去找80端口。因為url的格式就是這樣,平時訪問網頁,就是ip:port只不過port被隱藏了(因為是80,443常用端口,不需要寫)。[root@localhost ~]# curl 192.168.10.101/greet/1:5000
curl: (7) Failed to connect to 192.168.10.101 port 80 after 0 ms: Couldn't connect to serverURL的組成部分:協議(protocol):指定了資源應該使用的訪問方式,常見的協議有http、https、ftp等主機名(hostname):資源所在的服務器地址,可以是ip地址或域名。端口號(port):服務器上用于訪問資源的技術接口。路徑(path):資源在服務器上的具體位置。參數(parameters):提供給服務器的額外信息,通常以鍵值對的形式出現。查詢(query):通過?與url的其他部分分隔,用于提供額外的請求信息。片段(fragment):通常以#開始,指向資源內部的一個錨點,如網頁中的一個特定部分。url完整格式 http://www.hostname.com:80/index.html?lang=zh#contenthttp是協議,www.hostname.com是主機名,80是端口,/index.html是路徑,lang=zh是查詢參數,content是片段標識符。3、指定允許的請求方法。
[root@localhost ~]# vim a.py
from flask import Flask# 創建Flask應用實例
app=Flask(__name__)# 定義路由和視圖函數
@app.route('/')
def hello_world():return 'Hello,World!\n'@app.route('/greet/<name>')
def greet(name):return f'Hello,{name}!\n'@app.route('/submit',methods=['POST'])
def submit():return 'Form submitted successfully!\n' # Form是html里定義請求方式時用到的關鍵字。# 啟動應用
if __name__ == '__main__':app.run(host='0.0.0.0',port='5000',debug=True) [root@localhost ~]# python3 a.py * Serving Flask app 'a'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on all addresses (0.0.0.0)* Running on http://127.0.0.1:5000* Running on http://192.168.10.101:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 112-870-242[root@localhost ~]# curl 192.168.10.101:5000/submit
<!doctype html>
<html lang=en>
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
[root@localhost ~]# curl -XPOST 192.168.10.101:5000/submit
Form submitted successfully!4、使用jinja2模板渲染html[root@localhost ~]# mkdir templates
[root@localhost ~]# ls
anaconda-ks.cfg a.py templates # 模板文件與主程序(a.py必須在同一級目錄下,否則會找不到,名稱也必須叫templates,否則也會找不到。)
[root@localhost ~]# cd templates/
[root@localhost templates]# vim greet.html
<html lang="en">
<head><meta charset="UTF-8"><title>Flask Example</title>
</head>
<body><h1>Hello,{{ name }}!<h1> # {{ }} 這種格式是jinja2模板格式。name同樣是參數傳遞,ip/greet/name中的name會傳遞到這里。
</body>
</html>[root@localhost ~]# vim a.py
from flask import Flask
from flask import render_template# 創建Flask應用實例
app=Flask(__name__)# 定義路由和視圖函數
@app.route('/')
def hello_world():return 'Hello,World!\n'@app.route('/submit',methods=['POST'])
def submit():return 'Form submitted successfully!\n'@app.route('/greet/<name>')
def greet(name):return render_template('greet.html',name=name)# 啟動應用
if __name__ == '__main__':[root@localhost ~]# python3 a.py* Serving Flask app 'a'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on all addresses (0.0.0.0)* Running on http://127.0.0.1:5000* Running on http://192.168.10.101:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 112-870-242[root@localhost ~]# curl 192.168.10.101:5000/greet/aaa
<html lang="en">
<head> <meta charset="UTF-8"><title>Flask Example</title>
</head>
<body><h1>Hello,aaa!<h1>
</body>4、模板繼承與塊[root@localhost ~]# ls
anaconda-ks.cfg a.py templates
[root@localhost ~]# cat a.py
from flask import Flask
from flask import render_template# 創建Flask應用實例
app=Flask(__name__)# 定義路由和視圖函數
@app.route('/')
def hello_world():return 'Hello,World!\n'@app.route('/submit',methods=['POST'])
def submit():return 'Form submitted successfully!\n'@app.route('/index')
def index():return render_template('index.html')# 啟動應用
if __name__ == '__main__':app.run(host='0.0.0.0',port='5000',debug=True)[root@localhost ~]# cd templates/
[root@localhost templates]# ls
base.html greet.html index.html
[root@localhost templates]# cat base.html
<html lang="en">
<head><meta charset="UTF-8"><title>{% block title %}My Website{% endblock %}</title> # 定義塊開始與結束位置,并定義其中的內容。子模板引用父模板就是通過塊來引用的。
</head>
<body><header><h1>Welcome to My Website</h1></header><div> # div是html里的塊級元素,屬于容器,可包含標題、段落、表格等等。{% block content %}{% endblock %} # 定義塊開始與結束,content是內容。</div><footer><p>© 2025 My Website</p> # 頁腳處的信息。</footer>
</body>
</html>
[root@localhost templates]# cat index.html
{% extends 'base.html' %}{% block title %}Home{% endblock %} # 網站標簽處的顯示信息。例如百度的,百度一下,你就知道。{% block content %}<h2> Welcome to the homepage !</h2>###
{% extends 'base.html' %} 子模版繼承了base.html模板。
{% block title %}Home {% endblock %} 覆蓋父模板中的title塊。
{% block content %} 定義頁面的主要內容區域。[root@localhost ~]# python3 a.py* Serving Flask app 'a'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on all addresses (0.0.0.0)* Running on http://127.0.0.1:5000* Running on http://192.168.10.101:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 112-870-242[root@localhost ~]# curl 192.168.10.101:5000/index
<html lang="en">
<head><meta charset="UTF-8"><title>Home</title>
</head>
<body><header><h1>Welcome to My Website</h1></header><div><h2> Welcome to the homepage !</h2></div><footer><p>© 2025 My Website</p></footer>
</body>