Python3+Flask安裝使用教程詳解
一、Flask安裝環(huán)境配置
當(dāng)前我的開發(fā)環(huán)境是Miniconda3+PyCharm。開發(fā)環(huán)境其實無所謂,自己使用Python3+Nodepad都可以。安裝Flask庫:
pip install Flask
二、第一個Flask應(yīng)用程序
將以下內(nèi)容保存為helloworld.py:
# 導(dǎo)入Flask類
from flask import Flask
# 實例化,可視為固定格式
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)
直接運行該文件,然后訪問:http://127.0.0.1:5000/helloworld。結(jié)果如下圖:

三、get和post實現(xiàn)
3.1 創(chuàng)建用到的模板文件
Flask默認(rèn)到templates目錄下查找模板文件,在上邊helloworld.py同級目錄下創(chuàng)建templates文件夾。
在templates文件夾下創(chuàng)建get.html,寫入以下內(nèi)容:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>get請求示例</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,寫入以下內(nèi)容:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>post請求示例</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,寫入以下內(nèi)容:
<!-- Flask 使用Jinja2模板引擎,Jinja2模板引擎源于Django板模所以很多語法和Django是類似的 -->
<h1>{{ result }}</h1>
3.2 編寫相關(guān)的處理方法
在helloworld.py中添加get_html()、post_html()和deal_request()三個方法,更多說明見注釋。當(dāng)前helloworld.py內(nèi)容如下:
# 導(dǎo)入Flask類
from flask import Flask
from flask import render_template
from flask import request
# 實例化,可視為固定格式
app = Flask(__name__)
# route()方法用于設(shè)定路由;類似spring路由配置
#等價于在方法后寫:app.add_url_rule('/', 'helloworld', hello_world)
@app.route('/helloworld')
def hello_world():
return 'Hello, World!'
# 配置路由,當(dāng)請求get.html時交由get_html()處理
@app.route('/get.html')
def get_html():
# 使用render_template()方法重定向到templates文件夾下查找get.html文件
return render_template('get.html')
# 配置路由,當(dāng)請求post.html時交由post_html()處理
@app.route('/post.html')
def post_html():
# 使用render_template()方法重定向到templates文件夾下查找post.html文件
return render_template('post.html')
# 配置路由,當(dāng)請求deal_request時交由deal_request()處理
# 默認(rèn)處理get請求,我們通過methods參數(shù)指明也處理post請求
# 當(dāng)然還可以直接指定methods = ['POST']只處理post請求, 這樣下面就不需要if了
@app.route('/deal_request', methods = ['GET', 'POST'])
def deal_request():
if request.method == "GET":
# get通過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通過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 查看運行效果
重新運行helloworld.py。
當(dāng)前目錄結(jié)構(gòu)如下(.idea目錄不用管):

get.html如下:

get查詢結(jié)果如下:

post.html如下:

post查詢結(jié)果如下:

四、restful
所謂restful簡單理解就是以json等格式(而非以前的表單格式)發(fā)起請求,及以json等格式(而非以前的html)進(jìn)行響應(yīng)。
等下我們通過curl模擬rest請求,然后使用jsonify實現(xiàn)rest響應(yīng)。
4.1 服務(wù)端實現(xiàn)代碼
# 導(dǎo)入Flask類
from flask import Flask, jsonify
from flask import render_template
from flask import request
# 實例化,可視為固定格式
app = Flask(__name__)
# route()方法用于設(shè)定路由;類似spring路由配置
#等價于在方法后寫:app.add_url_rule('/', 'helloworld', hello_world)
@app.route('/helloworld')
def hello_world():
return 'Hello, World!'
# 配置路由,當(dāng)請求get.html時交由get_html()處理
@app.route('/get.html')
def get_html():
# 使用render_template()方法重定向到templates文件夾下查找get.html文件
return render_template('get.html')
# 配置路由,當(dāng)請求post.html時交由post_html()處理
@app.route('/post.html')
def post_html():
# 使用render_template()方法重定向到templates文件夾下查找post.html文件
return render_template('post.html')
# 配置路由,當(dāng)請求deal_request時交由deal_request()處理
# 默認(rèn)處理get請求,我們通過methods參數(shù)指明也處理post請求
# 當(dāng)然還可以直接指定methods = ['POST']只處理post請求, 這樣下面就不需要if了
@app.route('/deal_request', methods=['GET', 'POST'])
def deal_request():
if request.method == "GET":
# get通過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通過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():
"""
通過request.json以字典格式獲取post的內(nèi)容
通過jsonify實現(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 請求模擬
curl -H "Content-Type:application/json" -X POST --data '{"username": "ls","password":"toor"}' http://127.0.0.1:5000/rest_test
4.3 效果截圖

五、Flask與Django比較
5.1 Django配置復(fù)雜
如果對Django不是很了解,可以參看
Python3+PyCharm+Django+Django REST framework開發(fā)教程詳解
Python3+Django get/post請求實現(xiàn)教程詳解
僅從文章長度看就比這篇長很多,所以Django比Flask復(fù)雜(得多)是肯定的。更具體比較如下:
| 比較項 | Django | Flask | 復(fù)雜度比較 | 說明 |
| 項目創(chuàng)建 | Django需要用命令創(chuàng)建項目 | Flask直接編寫文件就可運行 | Django復(fù)雜 | Django需要用命令創(chuàng)建項目是因為要創(chuàng)建出整個項目框架 |
| 路由 | Django使用專門的urls.py文件 | Flask直接使用@app.route() | Django笨重 | Django類似Strut2的配置Flask類似Spring的配置,F(xiàn)lask感覺更好 |
| get和post | request.GET['name']和request.POST["name"] | request.args.get("name","")和request.form["q"] | 差不多 | Flask格式上不統(tǒng)一 |
| restful | 使用django-resful框架 | 使用jsonify | 差不多 | Flask不需要單建一個app,更直觀一些 |
| 數(shù)據(jù)庫操作 | django集成了對數(shù)據(jù)庫的操作 | Flask沒集成對數(shù)據(jù)庫的操作要另行直連或使用sqlalchemy | 差不多 | django復(fù)雜很大程度來源于對數(shù)據(jù)庫的集成。 |
5.2 Flask和Django各自適合使用場景
我們經(jīng)常會聽說這樣的一個近乎共識的觀點:Django是Python最流行的Web框架但配置比較復(fù)雜,F(xiàn)lask是一個輕量級的框架配置比較簡單如果項目比較小推薦使用Flask。
進(jìn)一步來說,F(xiàn)lask的輕量來源其“暫時不用的功能都先不做處理”,Django復(fù)雜來源于其“可能用到的功能都先集成”;隨著項目規(guī)模的擴(kuò)大最終Django有的東西Flask也都需要有。
所以,如果平時你用python是東用一個庫西用一個庫,東寫一個場景西寫一個場景,而不是專門開發(fā)web,那么你適合使用Flask,因為這樣你的學(xué)習(xí)成本低及以前的知識都能用上去。
本文主要講解了Python3+Flask安裝使用教程如果想查看更多關(guān)于Python3+Flask的知識文章請點擊下面相關(guān)文章
相關(guān)文章
Python使用QQ郵箱發(fā)送郵件報錯smtplib.SMTPAuthenticationError
這篇文章主要介紹了Python使用QQ郵箱發(fā)送郵件報錯smtplib.SMTPAuthenticationError,簡單介紹了python 發(fā)送郵件的步驟,需要的朋友可以參考下2019-12-12
tensorflow中的數(shù)據(jù)類型dtype用法說明
這篇文章主要介紹了tensorflow中的數(shù)據(jù)類型dtype用法說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
Python3查找列表中重復(fù)元素的個數(shù)的3種方法詳解
這篇文章主要介紹了Python3查找列表中重復(fù)元素的個數(shù)方法詳解,需要的朋友可以參考下2020-02-02
Python使用Matplotlib實現(xiàn)Logos設(shè)計代碼
這篇文章主要介紹了Python使用Matplotlib實現(xiàn)Logos設(shè)計代碼,具有一定借鑒價值,需要的朋友可以參考下。2017-12-12

