Python3+Flask安裝使用教程詳解
一、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類(lèi) from flask import Flask # 實(shí)例化,可視為固定格式 app = Flask(__name__) # route()方法用于設(shè)定路由;類(lèi)似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é)果如下圖:
三、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是類(lèi)似的 --> <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類(lèi) from flask import Flask from flask import render_template from flask import request # 實(shí)例化,可視為固定格式 app = Flask(__name__) # route()方法用于設(shè)定路由;類(lèi)似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目錄不用管):
get.html如下:
get查詢(xún)結(jié)果如下:
post.html如下:
post查詢(xún)結(jié)果如下:
四、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類(lèi) from flask import Flask, jsonify from flask import render_template from flask import request # 實(shí)例化,可視為固定格式 app = Flask(__name__) # route()方法用于設(shè)定路由;類(lèi)似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 效果截圖
五、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使用專(zhuān)門(mén)的urls.py文件 | Flask直接使用@app.route() | Django笨重 | Django類(lèi)似Strut2的配置Flask類(lèi)似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)景,而不是專(zhuān)門(mén)開(kāi)發(fā)web,那么你適合使用Flask,因?yàn)檫@樣你的學(xué)習(xí)成本低及以前的知識(shí)都能用上去。
本文主要講解了Python3+Flask安裝使用教程如果想查看更多關(guān)于Python3+Flask的知識(shí)文章請(qǐng)點(diǎn)擊下面相關(guān)文章
相關(guān)文章
Python使用QQ郵箱發(fā)送郵件報(bào)錯(cuò)smtplib.SMTPAuthenticationError
這篇文章主要介紹了Python使用QQ郵箱發(fā)送郵件報(bào)錯(cuò)smtplib.SMTPAuthenticationError,簡(jiǎn)單介紹了python 發(fā)送郵件的步驟,需要的朋友可以參考下2019-12-12django使用channels實(shí)現(xiàn)通信的示例
這篇文章主要介紹了django使用channels實(shí)現(xiàn)通信的示例,幫助大家更好的理解和學(xué)習(xí)django框架,感興趣的朋友可以了解下2020-10-10tensorflow中的數(shù)據(jù)類(lèi)型dtype用法說(shuō)明
這篇文章主要介紹了tensorflow中的數(shù)據(jù)類(lèi)型dtype用法說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05Python3查找列表中重復(fù)元素的個(gè)數(shù)的3種方法詳解
這篇文章主要介紹了Python3查找列表中重復(fù)元素的個(gè)數(shù)方法詳解,需要的朋友可以參考下2020-02-02Python抓取京東圖書(shū)評(píng)論數(shù)據(jù)
最近接了個(gè)項(xiàng)目,需要抓取京東圖書(shū)的評(píng)論,把代碼放出來(lái)給大家分享下,希望能有所幫助2014-08-08Python使用Matplotlib實(shí)現(xiàn)Logos設(shè)計(jì)代碼
這篇文章主要介紹了Python使用Matplotlib實(shí)現(xiàn)Logos設(shè)計(jì)代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12