在Flask中,視圖函數是處理用戶請求並返回響應的核心組件。它就像一個“橋樑”,連接用戶的訪問和頁面內容的生成。從最簡單的“Hello World”到動態展示數據,視圖函數的能力非常靈活。下面我們一步步探索視圖函數的用法。
一、視圖函數的“初體驗”:返回簡單內容¶
當用戶訪問某個URL時,Flask會自動調用對應的視圖函數。最簡單的視圖函數可以直接返回字符串,Flask會自動將其轉換爲HTML響應。
from flask import Flask
app = Flask(__name__) # 創建Flask應用實例
# 定義根路由(訪問http://localhost:5000/時觸發)
@app.route('/')
def index():
return "Hello, Flask!" # 返回字符串,Flask自動轉爲HTML
if __name__ == '__main__':
app.run(debug=True) # 啓動應用,debug=True開啓調試模式
運行代碼後,訪問根目錄會看到“Hello, Flask!”的文字,這就是視圖函數返回的結果。
二、返回靜態HTML:用模板渲染頁面¶
直接返回字符串適合簡單內容,但複雜HTML(如包含標題、列表等)更適合用模板管理。Flask通過render_template函數加載HTML模板文件,需要在項目中創建templates文件夾存放模板。
步驟1:創建模板文件
在項目根目錄下新建templates文件夾,創建index.html:
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>我的第一個頁面</title>
</head>
<body>
<h1>歡迎來到Flask世界!</h1>
<p>這是一個靜態HTML頁面。</p>
</body>
</html>
步驟2:視圖函數渲染模板
修改視圖函數,用render_template加載模板:
from flask import Flask, render_template # 導入render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html') # 加載templates文件夾中的index.html
if __name__ == '__main__':
app.run(debug=True)
此時訪問根目錄,頁面會顯示模板中的靜態HTML內容。
三、動態數據:讓頁面“活”起來¶
模板不僅能顯示靜態內容,還能通過視圖函數傳遞動態數據。Flask結合Jinja2模板引擎支持變量、循環、條件判斷等功能,讓頁面內容隨數據變化。
1. 模板變量:從視圖函數傳遞數據¶
視圖函數可以通過參數向模板傳遞動態內容,模板中用{{ 變量名 }}渲染。
示例:顯示當前時間
修改視圖函數,獲取當前時間並傳遞給模板:
from datetime import datetime # 導入時間模塊
@app.route('/time')
def show_time():
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 格式化時間
return render_template('time.html', current_time=current_time) # 傳遞變量
模板文件(templates/time.html):
<!DOCTYPE html>
<html>
<head>
<title>當前時間</title>
</head>
<body>
<h1>當前時間:{{ current_time }}</h1> <!-- 渲染變量 -->
</body>
</html>
訪問/time會顯示即時更新的時間。
2. 循環與條件:動態展示列表數據¶
通過Jinja2的{% for %}和{% if %}標籤,可以動態生成列表或條件內容。
示例:動態文章列表
視圖函數提供文章數據,模板用循環展示:
@app.route('/articles')
def articles():
# 模擬文章數據(列表包含多個字典)
article_list = [
{'id': 1, 'title': 'Flask入門教程', 'author': '小明'},
{'id': 2, 'title': 'Python基礎', 'author': '小紅'},
{'id': 3, 'title': '數據分析實戰', 'author': '小明'}
]
return render_template('articles.html', articles=article_list) # 傳遞列表
模板文件(templates/articles.html):
<!DOCTYPE html>
<html>
<head>
<title>文章列表</title>
</head>
<body>
<h1>我的文章</h1>
<ul>
{% for article in articles %} <!-- 循環遍歷文章列表 -->
<li>
<h3>{{ article.title }}</h3> <!-- 渲染文章標題 -->
<p>作者:{{ article.author }}</p>
</li>
{% endfor %}
</ul>
</body>
</html>
訪問/articles會看到動態生成的文章列表,每條文章內容隨數據變化。
3. URL參數:根據用戶輸入動態響應¶
視圖函數可以通過路由參數接收用戶輸入的URL內容,實現個性化響應。
示例:用戶個人頁面
路由中定義參數<user_id>,視圖函數接收參數並返回內容:
@app.route('/profile/<user_id>') # URL中的<user_id>爲動態參數
def profile(user_id):
return f"用戶ID:{user_id},這是用戶的個人主頁"
訪問/profile/123會顯示“用戶ID:123,這是用戶的個人主頁”。
4. 請求參數:處理用戶表單輸入¶
通過request對象獲取用戶通過URL參數或表單提交的數據,實現搜索、篩選等功能。
示例:搜索功能
獲取URL參數中的關鍵詞,動態返回搜索結果:
from flask import request # 導入request模塊
@app.route('/search')
def search():
keyword = request.args.get('keyword', default='') # 獲取URL參數中的keyword
return f"搜索結果:找到與“{keyword}”相關的內容..."
訪問/search?keyword=Flask會顯示“搜索結果:找到與“Flask”相關的內容…”。
四、綜合示例:動態博客列表¶
結合前面的知識點,我們做一個簡單的博客列表頁面,支持按作者搜索和動態展示文章。
項目結構:
myblog/
├── app.py
└── templates/
└── blog.html
app.py代碼:
from flask import Flask, render_template, request
app = Flask(__name__)
# 模擬文章數據
articles = [
{'id': 1, 'title': 'Flask基礎', 'author': '小明', 'date': '2023-01-01'},
{'id': 2, 'title': 'Python爬蟲', 'author': '小紅', 'date': '2023-01-02'},
{'id': 3, 'title': 'Flask進階', 'author': '小明', 'date': '2023-01-03'}
]
@app.route('/blog')
def blog():
# 獲取URL參數中的作者(默認爲空)
author = request.args.get('author', default='')
# 根據作者篩選文章
filtered_articles = [a for a in articles if a['author'] == author] if author else articles
return render_template('blog.html', articles=filtered_articles, author=author)
if __name__ == '__main__':
app.run(debug=True)
模板文件(templates/blog.html):
<!DOCTYPE html>
<html>
<head>
<title>博客列表</title>
</head>
<body>
<h1>博客列表</h1>
<!-- 搜索表單 -->
<form method="get" action="/blog">
<input type="text" name="author" placeholder="輸入作者名搜索" value="{{ author }}">
<input type="submit" value="搜索">
</form>
<!-- 文章列表 -->
<ul>
{% for article in articles %}
<li>
<h3>{{ article.title }}</h3>
<p>作者:{{ article.author }} | 日期:{{ article.date }}</p>
</li>
{% endfor %}
</ul>
</body>
</html>
訪問/blog可看到所有文章,輸入作者名(如“小明”)點擊搜索,會動態篩選出對應作者的文章。
總結¶
視圖函數是Flask的核心,通過它可以實現從簡單靜態頁面到複雜動態數據的展示。關鍵能力包括:
1. 返回內容:字符串(自動轉HTML)或模板渲染;
2. 動態數據:通過Jinja2模板變量、循環、條件展示內容;
3. 參數處理:URL參數和請求參數實現個性化響應。
掌握視圖函數後,你可以快速構建交互性強的Web應用,後續學習數據庫、用戶認證等功能時,視圖函數仍是核心基礎。