1. 程式人生 > >Flask高階應用01--環境搭建和例項化藍圖

Flask高階應用01--環境搭建和例項化藍圖

一、Flask簡介

Flask是一個基於Python實現的web開發的’微’框架,Flask和Django一樣,也是一個基於MVC設計模式的Web框架

[中文文件地址]http://docs.jinkan.org/docs/flask/
http://www.pythondoc.com/flask/index.html

flask流行的主要原因:

a)有非常齊全的官方文件,上手非常方便

b) 有非常好的拓展機制和第三方的拓展環境,工作中常見的軟體都有對應的拓展,自己動手實現拓展也很容易

c) 微型框架的形式給了開發者更大的選擇空間

二. 安裝flask

1虛擬環境搭建

vualenv --no-site-packages -p D:Python3\python.exe  flask  
#代表執行的時候沒有其他的包
#-p這樣安裝的可以指定對應的python版本,為指定的python版本來安裝虛擬環境

啟用windows下虛擬環境
cd Scripts
activate

2 安裝

pip install flask
  1. 基於flask的最小的應用(7行程式碼)

建立hello.py檔案(專業版pycharm可以直接建立)

from flask import Flask

app = Flask(__name__)

@app.route('/')
def gello_world():
	return 'Hello World'

if __name__ == '__main__':

	app.run()

執行:python hello.py

3.1 初始化

from flask import Flask

app = Flask(__name__)

Flask類建構函式唯一需要的引數就是應用程式的主模組或包。對於大多數應用程式,Python的name變數就是那個正確的、你需要傳遞的值。Flask使用這個引數來確定應用程式的根目錄,這樣以後可以相對這個路徑來找到資原始檔。

3.2 路由

@app.route('/')

客戶端例如web瀏覽器傳送 請求 給web服務,進而將它們傳送給Flask應用程式例項。應用程式例項需要知道對於各個URL請求需要執行哪些程式碼,所以它給Python函式建立了一個URLs對映。這些在URL和函式之間建立聯絡的操作被稱之為 路由 。

在Flask應程式中定義路由的最便捷的方式是通過顯示定義在應用程式例項之上的app.route裝飾器,註冊被裝飾的函式來作為一個 路由。

3.3 檢視函式

在上一個示例給應用程式的根URL註冊gello_world()函式作為事件的處理程式。如果這個應用程式被部署在伺服器上並綁定了 http://www.example.com/域名,然後在你的瀏覽器位址列中輸入 http://www.example.com/將觸發gello_world()來執行服務。客戶端接收到的這個函式的返回值被稱為 響應 。如果客戶端是web瀏覽器,響應則是顯示給使用者的文件。

類似於hello_world()的函式被稱作 檢視函式 。

3.4 動態名稱元件路由

你的Facebook個人資訊頁的URL是 http://www.facebook.com/ ,所以你的使用者名稱是它的一部分。Flask在路由裝飾器中使用特殊的語法支援這些型別的URLs。下面的示例定義了一個擁有動態名稱元件的路由:

@app.route('/hello/<name>')

def hello_world(name):

	return 'Hello World %s' % name

用尖括號括起來的部分是動態的部分,所以任何URLs匹配到靜態部分都將對映到這個路由。當檢視函式被呼叫,Flask傳送動態元件作為一個引數。在前面的示例的檢視函式中,這個引數是用於生成一個個性的問候作為響應。

在路由中動態元件預設為字串,但是可以定義為其他型別。例如,路由/user/int:id只匹配有一個整數在id動態段的URLs。Flask路由支援int、float

如下:

@app.route('/hello/<int:id>')

def hello_stu_id(id):

  return 'Hello World id: %s' % id

3.5 服務啟動

if __name__ == '__main__':

	app.run()

注意: name == 'main’在此處使用是用於確保web服務已經啟動當指令碼被立即執行。當指令碼被另一個指令碼匯入,它被看做父指令碼將啟動不同的服務,所以app.run()呼叫會被跳過。

一旦服務啟動,它將進入迴圈等待請求併為之服務。這個迴圈持續到應用程式停止,例如通過按下Ctrl-C。

有幾個選項引數可以給app.run()配置web服務的操作模式。在開發期間,可以很方便的開啟debug模式,將啟用 debugger 和 reloader 。這樣做是通過傳遞debug為True來實現的。

run()中引數有如下:

debug 是否開啟除錯模式,開啟後修改python的程式碼會自動重啟

port 啟動指定伺服器的埠號

host主機,預設是127.0.0.1
  1. 修改啟動方式,使用命令列引數啟動服務

4.1 安裝外掛

pip install flask-script

調整程式碼 manager = Manager(app=‘自定義的flask物件’)

啟動的地方 manager.run()

4.2 啟動命令

python hellow.py runserver -h 地址 -p 埠 -d -r

其中:-h表示地址。-p表示埠。-d表示debug模式。-r表示自動重啟

更換埠:

預設埠是5000

if __name__ == '__main__':
    # 修改啟動的ip和埠, debug模式
    # app.run(host='0.0.0.0', port=8080, debug=True)

    # python xxx.py runserver -h 0.0.0.0 -p 8080 -d
    manager.run()
  1. route規則

(1) 規則

寫法:converter:variable_name

converter型別:

string 字串
int 整形
float 浮點型
path 接受路徑,接收的時候是str,/也當做字串的一個字元
uuid 只接受uuid字串
any 可以同時指定多種路徑,進行限定

路由匹配規則

1. <id>: 預設接收的型別的str
2. <string:id>,指定id的型別為str
3. <int:id>, 指定id的型別為整型
4. <float:id>, 指定id的型別為浮點數
5. <path:path>, 指定接收的path為URL中的路徑
"""

例子:

@app.route('/helloint/<int:id>/')

@app.route('/getfloat/<float:price>/')

@app.route('/getstr/<string:name>/',methods=['GET', 'POST'])

@app.route('/getpath/<path:url_path>/')

@app.route('/getbyuuid/<uuid:uu>/',methods=['GET', 'POST'])

實現對應的檢視函式:

@blue.route('/hello/<name>/')
def hello_man(name):
    print(type(name))
    return 'hello name:%s type:%s' % (name, type(name))

@blue.route('/helloint/<int:id>/')
def hello_int(id):
    print(id)
    print(type(id))
    return 'hello int: %s' % (id)

@blue.route('/index/')
def index():
    return render_template('hello.html')

@blue.route('/getfloat/<float:price>/')
def hello_float(price):

    return 'float: %s' % price

@blue.route('/getstr/<string:name>/')
def hello_name(name):

    return 'hello name: %s' % name

@blue.route('/getpath/<path:url_path>/')
def hello_path(url_path):

    return 'path: %s' % url_path

@blue.route('/getuuid/')
def gello_get_uuid():
    a = uuid.uuid4()
    return str(a)

@blue.route('/getbyuuid/<uuid:uu>/')
def hello_uuid(uu):

    return 'uu:%s' % uu

(2) methods請求方法(是複數形式!!)

常用的請求型別有如下幾種

GET : 獲取
POST : 建立
PUT : 修改(全部屬性都修改)
DELETE : 刪除
PATCH : 修改(修改部分屬性)

定義url的請求型別:

@blue.route('/getrequest/', methods=['GET', 'POST'])

三、藍圖

  1. 什麼是藍圖

在Flask專案中可以用Blueprint(藍圖)實現模組化的應用,使用藍圖可以讓應用層次更清晰,開發者更容易去維護和開發專案。藍圖將作用於相同的URL字首的請求地址,將具有相同字首的請求都放在一個模組中,這樣查詢問題,一看路由就很快的可以找到對應的檢視,並解決問題了。

  1. 使用藍圖

(1) 安裝

pip install flask_blueprint

(2 )例項化藍圖應用

建立一個應用資料夾,設定好view.py檔案

from flask import Blueprint         #首先匯入藍圖

blue = Blueprint('app',__name__)    # 獲取藍圖物件,指定藍圖別名為app

注意:Blueprint中傳入了兩個引數,第一個是藍圖的名稱,第二個是藍圖所在的包或模組,name代表當前模組名或者包名

(3) 註冊(即:繫結藍圖blue和app關係,register和url_prefix)

app = Flask(__name__)

app.register_blueprint(blue, url_prefix='/user')

注意:第一個引數即我們定義初始化定義的藍圖物件,第二個引數url_prefix表示該藍圖下,所有的url請求必須以/user開始。這樣對一個模組的url可以很好的進行統一管理

3.檢視函式

修改檢視上的裝飾器,修改為@blue.router(‘/’)

@blue.route('/', methods=['GET', 'POST'])
def hello():
    # 檢視函式
    return 'Hello World'

注意:該方法對應的url為127.0.0.1:5000/user/

4.url_for反向解析(url_for; redirect)

語法:

url_for('藍圖中定義的第一個引數.函式名', 引數名=value)

定義跳轉的兩種方式:

from flask import url_for, redirect

@blue.route('/redirect/')
def make_redirect():
    # 第一種方法;(硬編碼url)
    return redirect('/hello/index/')
    # 方法二:(反向解析)===redirect(url_for('藍圖別名,跳轉的函式名'))
    return redirect(url_for('first.index'))