?概要
Python web 開發(fā)已經(jīng)有了相當(dāng)長的歷史,從最早的 CGI 腳本到現(xiàn)在的全棧 Web 框架,現(xiàn)在已經(jīng)成為了一種非常流行的方式。
Python 最早被用于 Web 開發(fā)是在 1995 年(90年代早期),當(dāng)時(shí)使用 CGI 腳本編寫動(dòng)態(tài) Web 頁面。2004 年 Django 框架發(fā)布,它是一個(gè)高度模塊化的框架,提供了許多開箱即用的功能,使得 Web 開發(fā)更加容易和快速。Flask 框架于 2010 年發(fā)布,是一個(gè)輕量級(jí)的框架,它提供了更少的默認(rèn)功能,但也更靈活,允許開發(fā)者根據(jù)需要添加或刪除功能。
1. 什么是 Flask?
Flask 是一款 Python 的輕量級(jí) Web 框架,它的特點(diǎn)是簡單易用、靈活性高。Flask 框架可以快速搭建 Web 應(yīng)用程序,是一個(gè)很好的選擇。Flask 框架的核心思想是 WSGI(Web Server Gateway Interface),它定義了 Web 服務(wù)器和 Web 應(yīng)用程序之間的通信協(xié)議。
1.1 Flask 的優(yōu)勢
-
簡單易用:Flask 框架的 API 簡單易用,開發(fā)者能夠快速上手。MVC設(shè)計(jì)模式。
-
靈活性高:Flask 框架的擴(kuò)展性高,可以根據(jù)實(shí)際需求進(jìn)行擴(kuò)展。
-
輕量級(jí):Flask 框架的代碼量小,運(yùn)行速度快。
-
文檔豐富:Flask 框架的文檔非常詳細(xì),開發(fā)者能夠輕松查找所需信息。
1.2 Flask 的缺點(diǎn)
-
輕量級(jí):Flask 框架的輕量級(jí)也是它的缺點(diǎn)之一,它的功能相對(duì)有限,需要自己進(jìn)行擴(kuò)展。
-
不適合大型應(yīng)用程序:Flask 框架適合小型應(yīng)用程序,對(duì)于大型應(yīng)用程序來說,可能會(huì)出現(xiàn)性能瓶頸。這時(shí)可以考慮Django。
1.3 Flask 的基礎(chǔ)組件
Flask 框架由以下幾個(gè)基礎(chǔ)組件組成:
-
路由:定義 URL 和視圖函數(shù)之間的映射關(guān)系。
-
視圖函數(shù):處理請(qǐng)求并返回響應(yīng)。
-
模板:生成 HTML 頁面。
-
表單:處理用戶提交的數(shù)據(jù)。
-
擴(kuò)展:實(shí)現(xiàn) Flask 框架的擴(kuò)展功能。
2. 基礎(chǔ)使用
2.1 安裝 Flask
在開始使用 Flask 之前,需要先安裝 Flask??梢允褂?pip 命令進(jìn)行安裝:
pip?install?Flask
2.2 Hello World
下面是一個(gè)簡單的示例,展示了如何使用 Flask 框架輸出 "Hello World"。
新建一個(gè)app.py文件,輸入如下內(nèi)容。
Linux下執(zhí)行:
export FLASK_APP=app.py
flask run
打開瀏覽器訪問 http://127.0.0.1:5000/ 即可。
如果是 windows 執(zhí)行:
set FLASK_APP=app.py
flask run
from?flask?import?Flask
app?=?Flask(__name__)
@app.route('/')
def?hello_world():
????return?'Hello,?World!'
2.3 路由和視圖函數(shù)
在 Flask 中,路由和視圖函數(shù)是緊密相關(guān)的。路由用于將 URL 映射到視圖函數(shù)上,視圖函數(shù)則處理請(qǐng)求并返回響應(yīng)。為了實(shí)現(xiàn)路由和視圖函數(shù),我們可以使用 Flask 中的?@app.route
?裝飾器。下面是一個(gè)簡單的示例:
from?flask?import?Flask
app?=?Flask(__name__)
@app.route('/')
def?index():
????return?'This?is?the?index?page.'
@app.route('/hello')
def?hello():
????return?'Hello,?World!'
@app.route('/')
?和?@app.route('/hello')
?分別定義了兩個(gè)路由,index()
?和?hello()
?則是兩個(gè)視圖函數(shù)。
2.4 模板
模板是 Flask 中生成 HTML 頁面的一種方式。Flask 支持多種模板引擎,包括 Jinja2、Mako、Tenjin 等。在本文中,我們使用 Jinja2 作為模板引擎。
下面是一個(gè)簡單的示例,展示了如何使用模板生成 HTML 頁面:
from?flask?import?Flask,?render_template
app?=?Flask(__name__)
@app.route('/')
def?index():
????return?render_template('index.html',?title='Home')
@app.route('/hello')
def?hello():
????return?render_template('hello.html',?name='Flask')
render_template()
?函數(shù)用于渲染模板,第一個(gè)參數(shù)指定模板名稱,第二個(gè)參數(shù)則是模板中使用的變量。
2.5 靜態(tài)文件
靜態(tài)文件包括 CSS、JavaScript、圖片等。在 Flask 中,可以使用?url_for()
?函數(shù)生成靜態(tài)文件的 URL。
下面是一個(gè)簡單的示例:
<!DOCTYPE?html>
<html>
<head>
????<meta?charset="UTF-8">
????<title>{{?title?}}</title>
????<link?rel="stylesheet"?href="{{?url_for('static',?filename='style.css')?}}">
</head>
<body>
????<h1>{{?title?}}</h1>
????<p>Hello,?Flask!</p>
</body>
</html>
url_for('static', filename='style.css')
?生成了靜態(tài)文件?style.css
?的 URL。
2.6 表單
表單是 Web 應(yīng)用程序中常用的一種交互方式。在 Flask 中,可以使用?request
?對(duì)象獲取用戶提交的表單數(shù)據(jù)。
下面是一個(gè)簡單的示例:
from?flask?import?Flask,?request
app?=?Flask(__name__)
@app.route('/login',?methods=['GET',?'POST'])
def?login():
????if?request.method?==?'POST':
????????username?=?request.form['username']
????????password?=?request.form['password']
????????if?username?==?'admin'?and?password?==?'password':
????????????return?'Login?success!'
????????else:
????????????return?'Invalid?username?or?password.'
????else:
????????return?'''
????????????<form?method="post">
????????????????<label>Username:</label>
????????????????<input?type="text"?name="username">
????????????????<label>Password:</label>
????????????????<input?type="password"?name="password">
????????????????<input?type="submit"?value="Login">
????????????</form>
????????'''
request.form
?可以獲取 POST 請(qǐng)求提交的表單數(shù)據(jù)。
3. 實(shí)戰(zhàn)案例:構(gòu)建一個(gè) Todo (待辦) 應(yīng)用
接下來,我們將通過一個(gè)實(shí)戰(zhàn)案例來介紹如何使用 Flask 框架構(gòu)建一個(gè) Todo 應(yīng)用。
3.1 數(shù)據(jù)庫設(shè)計(jì)
首先,我們需要設(shè)計(jì)數(shù)據(jù)庫。在本文中,我們使用 MySQL 作為數(shù)據(jù)庫。下面是數(shù)據(jù)庫的設(shè)計(jì):
CREATE?TABLE?`todos`?(
??`id`?int(11)?NOT?NULL?AUTO_INCREMENT,
??`title`?varchar(255)?NOT?NULL,
??`completed`?tinyint(1)?NOT?NULL?DEFAULT?'0',
??PRIMARY?KEY?(`id`)
)?ENGINE=InnoDB?DEFAULT?CHARSET=utf8mb4;
3.2 后端實(shí)現(xiàn)
接下來實(shí)現(xiàn)后端的功能:
from?flask?import?Flask,?render_template,?request,?redirect,?url_for
import?pymysql.cursors
app?=?Flask(__name__)
app.config['SECRET_KEY']?=?'secret'
connection?=?pymysql.connect(
????host='localhost',
????user='root',
????password='password',
????db='todo',
????charset='utf8mb4',
????cursorclass=pymysql.cursors.DictCursor
)
@app.route('/')
def?index():
????with?connection.cursor()?as?cursor:
????????cursor.execute('SELECT?*?FROM?`todos`')
????????todos?=?cursor.fetchall()
????return?render_template('index.html',?todos=todos)
@app.route('/add',?methods=['POST'])
def?add():
????title?=?request.form['title']
????with?connection.cursor()?as?cursor:
????????cursor.execute('INSERT?INTO?`todos`?(`title`)?VALUES?(%s)',?title)
????????connection.commit()
????return?redirect(url_for('index'))
@app.route('/toggle/<int:todo_id>',?methods=['POST'])
def?toggle(todo_id):
????with?connection.cursor()?as?cursor:
????????cursor.execute('SELECT?`completed`?FROM?`todos`?WHERE?`id`?=?%s',?todo_id)
????????completed?=?cursor.fetchone()['completed']
????????cursor.execute('UPDATE?`todos`?SET?`completed`?=?%s?WHERE?`id`?=?%s',?(not?completed,?todo_id))
????????connection.commit()
????return?redirect(url_for('index'))
@app.route('/delete/<int:todo_id>',?methods=['POST'])
def?delete(todo_id):
????with?connection.cursor()?as?cursor:
????????cursor.execute('DELETE?FROM?`todos`?WHERE?`id`?=?%s',?todo_id)
????????connection.commit()
????return?redirect(url_for('index'))
解析:建立數(shù)據(jù)庫連接,并定義四個(gè)路由:
-
/
:顯示所有的 Todo。 -
/add
:添加一個(gè) Todo。 -
/toggle/
:標(biāo)記一個(gè) Todo 是否已完成。 -
/delete/
:刪除一個(gè) Todo。
3.3 前端實(shí)現(xiàn)
最后實(shí)現(xiàn)前端的功能:
<!DOCTYPE?html>
<html>
<head>
????<meta?charset="UTF-8">
????<title>Todo</title>
????<style>
????????.completed?{
????????????text-decoration:?line-through;
????????}
????</style>
</head>
<body>
????<h1>Todo</h1>
????<form?method="post"?action="{{?url_for('add')?}}">
????????<label>Title:</label>
????????<input?type="text"?name="title">
????????<input?type="submit"?value="Add">
????</form>
????<ul>
????????{%?for?todo?in?todos?%}
????????????<li{%?if?todo.completed?%}?class="completed"{%?endif?%}>
????????????????<form?method="post"?action="{{?url_for('toggle',?todo_id=todo.id)?}}">
????????????????????<input?type="checkbox"?name="completed"?{%?if?todo.completed?%}checked{%?endif?%}>
????????????????????{{?todo.title?}}
????????????????</form>
????????????????<form?method="post"?action="{{?url_for('delete',?todo_id=todo.id)?}}">
????????????????????<input?type="submit"?value="Delete">
????????????????</form>
????????????</li>
????????{%?else?%}
????????????<p>No?todos.</p>
????????{%?endfor?%}
????</ul>
</body>
</html>
我們使用了 Jinja2 模板引擎,展示了 Todo 列表、添加 Todo、標(biāo)記 Todo 是否已完成、刪除 Todo 等功能。文章來源:http://www.zghlxwxcb.cn/news/detail-722966.html
4. 技術(shù)總結(jié)
今天介紹了如何使用 Flask 框架進(jìn)行 Web 開發(fā),并實(shí)戰(zhàn)開發(fā)了一個(gè)輕量級(jí)的web應(yīng)用。Flask 是一款 Python 的輕量級(jí) Web 框架,具有簡單易用、靈活性高等優(yōu)點(diǎn),初學(xué)者也能快速上手。文章來源地址http://www.zghlxwxcb.cn/news/detail-722966.html
到了這里,關(guān)于Python web實(shí)戰(zhàn) | 用 Flask 框架快速構(gòu)建 Web 應(yīng)用【實(shí)戰(zhàn)】的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!