一、Flask安裝環(huán)境配置
當(dāng)前我的開(kāi)發(fā)環(huán)境是Miniconda3+PyCharm。開(kāi)發(fā)環(huán)境其實(shí)無(wú)所謂,自己使用Python3+Nodepad都可以。安裝Flask庫(kù):
pip install Flask
二、第一個(gè)Flask應(yīng)用程序
將以下內(nèi)容保存為helloworld.py:
# 導(dǎo)入Flask類
from flask import Flask
# 實(shí)例化,可視為固定格式
app = Flask(__name__)
# route()方法用于設(shè)定路由;類似spring路由配置
@app.route('/helloworld')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
# app.run(host, port, debug, options)
# 默認(rèn)值:host="127.0.0.1", port=5000, debug=False
app.run(host="0.0.0.0", port=5000)
直接運(yùn)行該文件,然后訪問(wèn):http://127.0.0.1:5000/helloworld。結(jié)果如下圖:
![](/d/20211017/8cf60d91331f435ed3d978c716aff9af.gif)
三、get和post實(shí)現(xiàn)
3.1 創(chuàng)建用到的模板文件
Flask默認(rèn)到templates目錄下查找模板文件,在上邊helloworld.py同級(jí)目錄下創(chuàng)建templates文件夾。
在templates文件夾下創(chuàng)建get.html,寫(xiě)入以下內(nèi)容:
!DOCTYPE html>
html>
head>
meta charset="utf-8">
title>get請(qǐng)求示例/title>
/head>
body>
form action="/deal_request" method="get">
input type="text" name="q" />
input type="submit" value="搜索" />
/form>
/body>
/html>
再在templates文件夾下創(chuàng)建post.html,寫(xiě)入以下內(nèi)容:
!DOCTYPE html>
html>
head>
meta charset="utf-8">
title>post請(qǐng)求示例/title>
/head>
body>
form action="/deal_request" method="post">
input type="text" name="q" />
input type="submit" value="搜索" />
/form>
/body>
/html>
最后在templates文件夾下創(chuàng)建result.html,寫(xiě)入以下內(nèi)容:
!-- Flask 使用Jinja2模板引擎,Jinja2模板引擎源于Django板模所以很多語(yǔ)法和Django是類似的 -->
h1>{{ result }}/h1>
3.2 編寫(xiě)相關(guān)的處理方法
在helloworld.py中添加get_html()、post_html()和deal_request()三個(gè)方法,更多說(shuō)明見(jiàn)注釋。當(dāng)前helloworld.py內(nèi)容如下:
# 導(dǎo)入Flask類
from flask import Flask
from flask import render_template
from flask import request
# 實(shí)例化,可視為固定格式
app = Flask(__name__)
# route()方法用于設(shè)定路由;類似spring路由配置
#等價(jià)于在方法后寫(xiě):app.add_url_rule('/', 'helloworld', hello_world)
@app.route('/helloworld')
def hello_world():
return 'Hello, World!'
# 配置路由,當(dāng)請(qǐng)求get.html時(shí)交由get_html()處理
@app.route('/get.html')
def get_html():
# 使用render_template()方法重定向到templates文件夾下查找get.html文件
return render_template('get.html')
# 配置路由,當(dāng)請(qǐng)求post.html時(shí)交由post_html()處理
@app.route('/post.html')
def post_html():
# 使用render_template()方法重定向到templates文件夾下查找post.html文件
return render_template('post.html')
# 配置路由,當(dāng)請(qǐng)求deal_request時(shí)交由deal_request()處理
# 默認(rèn)處理get請(qǐng)求,我們通過(guò)methods參數(shù)指明也處理post請(qǐng)求
# 當(dāng)然還可以直接指定methods = ['POST']只處理post請(qǐng)求, 這樣下面就不需要if了
@app.route('/deal_request', methods = ['GET', 'POST'])
def deal_request():
if request.method == "GET":
# get通過(guò)request.args.get("param_name","")形式獲取參數(shù)值
get_q = request.args.get("q","")
return render_template("result.html", result=get_q)
elif request.method == "POST":
# post通過(guò)request.form["param_name"]形式獲取參數(shù)值
post_q = request.form["q"]
return render_template("result.html", result=post_q)
if __name__ == '__main__':
# app.run(host, port, debug, options)
# 默認(rèn)值:host=127.0.0.1, port=5000, debug=false
app.run()
3.3 查看運(yùn)行效果
重新運(yùn)行helloworld.py。
當(dāng)前目錄結(jié)構(gòu)如下(.idea目錄不用管):
![](/d/20211017/89428cce36c7334516df341ea3ebf02f.gif)
get.html如下:
![](/d/20211017/4d27e810fba11df1f1bd2c9d55547b36.gif)
get查詢結(jié)果如下:
![](/d/20211017/4bb356de2b59ad4da6ecb2864237b829.gif)
post.html如下:
![](/d/20211017/070dbdf4f2c3c352f7f531a09dcd56e0.gif)
post查詢結(jié)果如下:
![](/d/20211017/89e403294606f8e04e3745fa1a090622.gif)
四、restful
所謂restful簡(jiǎn)單理解就是以json等格式(而非以前的表單格式)發(fā)起請(qǐng)求,及以json等格式(而非以前的html)進(jìn)行響應(yīng)。
等下我們通過(guò)curl模擬rest請(qǐng)求,然后使用jsonify實(shí)現(xiàn)rest響應(yīng)。
4.1 服務(wù)端實(shí)現(xiàn)代碼
# 導(dǎo)入Flask類
from flask import Flask, jsonify
from flask import render_template
from flask import request
# 實(shí)例化,可視為固定格式
app = Flask(__name__)
# route()方法用于設(shè)定路由;類似spring路由配置
#等價(jià)于在方法后寫(xiě):app.add_url_rule('/', 'helloworld', hello_world)
@app.route('/helloworld')
def hello_world():
return 'Hello, World!'
# 配置路由,當(dāng)請(qǐng)求get.html時(shí)交由get_html()處理
@app.route('/get.html')
def get_html():
# 使用render_template()方法重定向到templates文件夾下查找get.html文件
return render_template('get.html')
# 配置路由,當(dāng)請(qǐng)求post.html時(shí)交由post_html()處理
@app.route('/post.html')
def post_html():
# 使用render_template()方法重定向到templates文件夾下查找post.html文件
return render_template('post.html')
# 配置路由,當(dāng)請(qǐng)求deal_request時(shí)交由deal_request()處理
# 默認(rèn)處理get請(qǐng)求,我們通過(guò)methods參數(shù)指明也處理post請(qǐng)求
# 當(dāng)然還可以直接指定methods = ['POST']只處理post請(qǐng)求, 這樣下面就不需要if了
@app.route('/deal_request', methods=['GET', 'POST'])
def deal_request():
if request.method == "GET":
# get通過(guò)request.args.get("param_name","")形式獲取參數(shù)值
get_q = request.args.get("q","")
return render_template("result.html", result=get_q)
elif request.method == "POST":
# post通過(guò)request.form["param_name"]形式獲取參數(shù)值
post_q = request.form["q"]
return render_template("result.html", result=post_q)
@app.route('/rest_test',methods=['POST'])
def hello_world1():
"""
通過(guò)request.json以字典格式獲取post的內(nèi)容
通過(guò)jsonify實(shí)現(xiàn)返回json格式
"""
post_param = request.json
result_dict = {
"result_code": 2000,
"post_param": post_param
}
return jsonify(result_dict)
if __name__ == '__main__':
# app.run(host, port, debug, options)
# 默認(rèn)值:host=127.0.0.1, port=5000, debug=false
app.run()
4.2 請(qǐng)求模擬
curl -H "Content-Type:application/json" -X POST --data '{"username": "ls","password":"toor"}' http://127.0.0.1:5000/rest_test
4.3 效果截圖
![](/d/20211017/510ac59d10fe8fd9a156b578aebe8ace.gif)
五、Flask與Django比較
5.1 Django配置復(fù)雜
如果對(duì)Django不是很了解,可以參看
Python3+PyCharm+Django+Django REST framework開(kāi)發(fā)教程詳解
Python3+Django get/post請(qǐng)求實(shí)現(xiàn)教程詳解
僅從文章長(zhǎng)度看就比這篇長(zhǎng)很多,所以Django比Flask復(fù)雜(得多)是肯定的。更具體比較如下:
比較項(xiàng) |
Django |
Flask |
復(fù)雜度比較 |
說(shuō)明 |
項(xiàng)目創(chuàng)建 |
Django需要用命令創(chuàng)建項(xiàng)目 |
Flask直接編寫(xiě)文件就可運(yùn)行 |
Django復(fù)雜 |
Django需要用命令創(chuàng)建項(xiàng)目是因?yàn)橐獎(jiǎng)?chuàng)建出整個(gè)項(xiàng)目框架 |
路由 |
Django使用專門的urls.py文件 |
Flask直接使用@app.route() |
Django笨重 |
Django類似Strut2的配置Flask類似Spring的配置,F(xiàn)lask感覺(jué)更好 |
get和post |
request.GET['name']和request.POST["name"] |
request.args.get("name","")和request.form["q"] |
差不多 |
Flask格式上不統(tǒng)一 |
restful |
使用django-resful框架 |
使用jsonify |
差不多 |
Flask不需要單建一個(gè)app,更直觀一些 |
數(shù)據(jù)庫(kù)操作 |
django集成了對(duì)數(shù)據(jù)庫(kù)的操作 |
Flask沒(méi)集成對(duì)數(shù)據(jù)庫(kù)的操作要另行直連或使用sqlalchemy |
差不多 |
django復(fù)雜很大程度來(lái)源于對(duì)數(shù)據(jù)庫(kù)的集成。 |
5.2 Flask和Django各自適合使用場(chǎng)景
我們經(jīng)常會(huì)聽(tīng)說(shuō)這樣的一個(gè)近乎共識(shí)的觀點(diǎn):Django是Python最流行的Web框架但配置比較復(fù)雜,F(xiàn)lask是一個(gè)輕量級(jí)的框架配置比較簡(jiǎn)單如果項(xiàng)目比較小推薦使用Flask。
進(jìn)一步來(lái)說(shuō),F(xiàn)lask的輕量來(lái)源其“暫時(shí)不用的功能都先不做處理”,Django復(fù)雜來(lái)源于其“可能用到的功能都先集成”;隨著項(xiàng)目規(guī)模的擴(kuò)大最終Django有的東西Flask也都需要有。
所以,如果平時(shí)你用python是東用一個(gè)庫(kù)西用一個(gè)庫(kù),東寫(xiě)一個(gè)場(chǎng)景西寫(xiě)一個(gè)場(chǎng)景,而不是專門開(kāi)發(fā)web,那么你適合使用Flask,因?yàn)檫@樣你的學(xué)習(xí)成本低及以前的知識(shí)都能用上去。
本文主要講解了Python3+Flask安裝使用教程如果想查看更多關(guān)于Python3+Flask的知識(shí)文章請(qǐng)點(diǎn)擊下面相關(guān)文章
您可能感興趣的文章:- python3-flask-3將信息寫(xiě)入日志的實(shí)操方法
- CentOS7部署Flask(Apache、mod_wsgi、Python36、venv)
- python3使用flask編寫(xiě)注冊(cè)post接口的方法
- python3 flask實(shí)現(xiàn)文件上傳功能
- win系統(tǒng)下為Python3.5安裝flask-mongoengine 庫(kù)