佳木斯湛栽影视文化发展公司

主頁(yè) > 知識(shí)庫(kù) > Python3+Flask安裝使用教程詳解

Python3+Flask安裝使用教程詳解

熱門標(biāo)簽:硅谷的囚徒呼叫中心 客戶服務(wù) 呼叫中心市場(chǎng)需求 語(yǔ)音系統(tǒng) Win7旗艦版 電話運(yùn)營(yíng)中心 百度AI接口 企業(yè)做大做強(qiáng)

 一、Flask安裝環(huán)境配置

當(dāng)前我的開發(fā)環(huán)境是Miniconda3+PyCharm。開發(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é)果如下圖:

三、get和post實(shí)現(xiàn)

3.1 創(chuàng)建用到的模板文件

Flask默認(rèn)到templates目錄下查找模板文件,在上邊helloworld.py同級(jí)目錄下創(chuàng)建templates文件夾。

在templates文件夾下創(chuàng)建get.html,寫入以下內(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,寫入以下內(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,寫入以下內(nèi)容:

!-- Flask 使用Jinja2模板引擎,Jinja2模板引擎源于Django板模所以很多語(yǔ)法和Django是類似的 -->
h1>{{ result }}/h1>

3.2 編寫相關(guān)的處理方法

在helloworld.py中添加get_html()、post_html()和deal_request()三個(gè)方法,更多說(shuō)明見注釋。當(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à)于在方法后寫: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查詢結(jié)果如下:

post.html如下:

post查詢結(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類
from flask import Flask, jsonify
from flask import render_template
from flask import request

# 實(shí)例化,可視為固定格式
app = Flask(__name__)

# route()方法用于設(shè)定路由;類似spring路由配置
#等價(jià)于在方法后寫: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開發(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直接編寫文件就可運(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ì)聽說(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ù),東寫一個(gè)場(chǎng)景西寫一個(gè)場(chǎng)景,而不是專門開發(fā)web,那么你適合使用Flask,因?yàn)檫@樣你的學(xué)習(xí)成本低及以前的知識(shí)都能用上去。

本文主要講解了Python3+Flask安裝使用教程如果想查看更多關(guān)于Python3+Flask的知識(shí)文章請(qǐng)點(diǎn)擊下面相關(guān)文章

您可能感興趣的文章:
  • python3-flask-3將信息寫入日志的實(shí)操方法
  • CentOS7部署Flask(Apache、mod_wsgi、Python36、venv)
  • python3使用flask編寫注冊(cè)post接口的方法
  • python3 flask實(shí)現(xiàn)文件上傳功能
  • win系統(tǒng)下為Python3.5安裝flask-mongoengine 庫(kù)

標(biāo)簽:崇左 山西 長(zhǎng)沙 山西 海南 濟(jì)南 安康 喀什

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python3+Flask安裝使用教程詳解》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    旺苍县| 鄂尔多斯市| 凤凰县| 耿马| 肥西县| 绿春县| 玉田县| 延寿县| 闽清县| 丽江市| 阳曲县| 时尚| 鹤山市| 全南县| 白朗县| 太仆寺旗| 辽宁省| 昭觉县| 林西县| 秭归县| 富阳市| 札达县| 绩溪县| 府谷县| 阿尔山市| 玉林市| 深泽县| 青川县| 江津市| 麻江县| 久治县| 山阳县| 尼玛县| 昂仁县| 连州市| 慈溪市| 绥江县| 定结县| 吉木萨尔县| 谷城县| 中卫市|