主頁 > 知識庫 > Python3+Flask安裝使用教程詳解

Python3+Flask安裝使用教程詳解

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

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

當前我的開發(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)
 # 默認值: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默認到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()三個方法,更多說明見注釋。當前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!'

# 配置路由,當請求get.html時交由get_html()處理
@app.route('/get.html')
def get_html():
 # 使用render_template()方法重定向到templates文件夾下查找get.html文件
 return render_template('get.html')

# 配置路由,當請求post.html時交由post_html()處理
@app.route('/post.html')
def post_html():
 # 使用render_template()方法重定向到templates文件夾下查找post.html文件
 return render_template('post.html')

# 配置路由,當請求deal_request時交由deal_request()處理
# 默認處理get請求,我們通過methods參數(shù)指明也處理post請求
# 當然還可以直接指定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)
 # 默認值:host=127.0.0.1, port=5000, debug=false
 app.run()

3.3 查看運行效果

重新運行helloworld.py。

當前目錄結(jié)構(gòu)如下(.idea目錄不用管):

get.html如下:

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

post.html如下:

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

四、restful

所謂restful簡單理解就是以json等格式(而非以前的表單格式)發(fā)起請求,及以json等格式(而非以前的html)進行響應(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!'

# 配置路由,當請求get.html時交由get_html()處理
@app.route('/get.html')
def get_html():
 # 使用render_template()方法重定向到templates文件夾下查找get.html文件
 return render_template('get.html')

# 配置路由,當請求post.html時交由post_html()處理
@app.route('/post.html')
def post_html():
 # 使用render_template()方法重定向到templates文件夾下查找post.html文件
 return render_template('post.html')

# 配置路由,當請求deal_request時交由deal_request()處理
# 默認處理get請求,我們通過methods參數(shù)指明也處理post請求
# 當然還可以直接指定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)
 # 默認值: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。

進一步來說,F(xiàn)lask的輕量來源其“暫時不用的功能都先不做處理”,Django復(fù)雜來源于其“可能用到的功能都先集成”;隨著項目規(guī)模的擴大最終Django有的東西Flask也都需要有。

所以,如果平時你用python是東用一個庫西用一個庫,東寫一個場景西寫一個場景,而不是專門開發(fā)web,那么你適合使用Flask,因為這樣你的學(xué)習(xí)成本低及以前的知識都能用上去。

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

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

標簽:崇左 山西 長沙 山西 海南 濟南 安康 喀什

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

    • 400-1100-266