1. 程式人生 > >Flask學習筆記之——藍圖、基於DBUtils實現資料庫連線池、上下文管理等

Flask學習筆記之——藍圖、基於DBUtils實現資料庫連線池、上下文管理等

面向物件知識回顧

子類繼承父類的三種方式

class Dog(Animal): #子類  派生類
    def __init__(self,name,breed, life_value,aggr):
        # Animal.__init__(self,name,breed, life_value,aggr)#讓子類執行父類的方法 就是父類名.方法名(引數),連self都得傳
        super().__init__(name,life_value,aggr) #super關鍵字  ,都不用傳self了,在新式類裡的
        # super(Dog,self).__init__(name,life_value,aggr)  #上面super是簡寫
        self.breed = breed
    def bite(self,person):   #狗的派生方法
        person.life_value -= self.aggr
    def eat(self):  #父類方法的重寫
        super().eat()
        print('dog is eating')

物件通過索引設定值的三種方式

  • 方式一:重寫__setitem__方法
class Foo(object):
    def __setitem__(self, key, value):
        print(key,value)

obj = Foo()
obj["xxx"] = 123   #給物件賦值就會去執行__setitem__方法
  • 方式二:繼承dict
class Foo(dict):
    pass

obj = Foo()
obj["xxx"] = 123
print(obj)
  • 方式三:繼承dict,重寫__init__方法的時候,記得要繼承父類的__init__方法
class Foo(dict):
    def __init__(self,val):
        # dict.__init__(self, val)#繼承父類方式一
        # super().__init__(val)  #繼承父類方式二
        super(Foo,self).__init__(val)#繼承父類方式三
obj = Foo({"xxx":123})
print(obj)

Flask設定配置檔案的幾種方式

==========方式一:============
 app.config['SESSION_COOKIE_NAME'] = 'session_lvning'  #這種方式要把所有的配置都放在一個資料夾裡面,看起來會比較亂,所以選擇下面的方式
==========方式二:==============
app.config.from_pyfile('settings.py')  #找到配置檔案路徑,建立一個模組,開啟檔案,並獲取所有的內容,再將配置檔案中的所有值,都封裝到上一步建立的配置檔案模板中

print(app.config.get("CCC"))
=========方式三:物件的方式============
 import os 
 os.environ['FLAKS-SETTINGS'] = 'settings.py'
 app.config.from_envvar('FLAKS-SETTINGS') 

===============方式四(推薦):字串的方式,方便操作,不用去改配置,直接改變字串就行了 ==============
app.config.from_object('settings.DevConfig')

----------settings.DevConfig----------
from app import app
class BaseConfig(object):
    NNN = 123  #注意是大寫
    SESSION_COOKIE_NAME = "session_sss"

class TestConfig(BaseConfig):
    DB = "127.0.0.1"

class DevConfig(BaseConfig):
    DB = "52.5.7.5"

class ProConfig(BaseConfig):
    DB = "55.4.22.4"

要想在檢視函式中獲取配置檔案的值,都是通過app.config來拿。但是如果檢視函式和Flask建立的物件app不在一個模組。就得通過模組匯入來拿。為了解決這個麻煩的操作,Flask提供了current_app,這個就是當前的app物件,用current_app.config就能檢視到了當前app的所有的配置檔案。

from flask import Flask,current_app
 
@app.route('/index',methods=["GET","POST"])
def index():
    print(current_app.config)   #當前的app的所有配置
    session["xx"] = "fdvbn"
    return "index"

藍圖

如果程式碼非常多,要進行歸類。不同的功能放在不同的檔案,把相關的檢視函式也放進去。藍圖也就是對Flask的目錄結構進行分配(應用於小,中型的程式)。

import fcrm
if __name__ == '__main__':
    fcrm.app.run()

__init__.py (只要一匯入fcrm就會執行__init__.py檔案)

from flask import Flask
#匯入accout 和order
from fcrm.views import accout
from fcrm.views import order
app = Flask(__name__)
print(app.root_path)  #根目錄

app.register_blueprint(accout.accout)  #把藍圖註冊到app裡面,accout.accout是建立的藍圖物件
app.register_blueprint(order.order)
rom flask import  Blueprint,render_template
accout = Blueprint("accout",__name__)

@accout.route('/accout')
def xx():
    return "accout"

@accout.route("/login")
def login():
    return render_template("login.html")
from flask import Blueprint
order = Blueprint("order",__name__)

@order.route('/order')
def register():   #注意檢視函式的名字不能和藍圖物件的名字一樣
    return "order

使用藍圖時需要注意的:
在這裡插入圖片描述
大型:
在這裡插入圖片描述 在這裡插入圖片描述 在這裡插入圖片描述

資料庫連線池

Flask中是沒有ORM的,如果在Flask裡面連線資料庫有兩種方式:

一:pymysql
二:SQLAlchemy
        是python 操作資料庫的一個庫。能夠進行 orm 對映官方文件 sqlchemy
        SQLAlchemy“採用簡單的Python語言,為高效和高效能的資料庫訪問設計,實現了完整的企業級持久模型”。SQLAlchemy的理念是,SQL資料庫的量級和效能重要於物件集合;而物件集合的抽象又重要於表和行。

連線池原理

    - BDUtils資料庫連結池  
                - 模式一:基於threaing.local實現為每一個執行緒建立一個連線,關閉是
                  偽關閉,當前執行緒可以重複
                - 模式二:連線池原理
                        - 可以設定連線池中最大連線數    9
                        - 預設啟動時,連線池中建立連線  5
                        
                        - 如果有三個執行緒來資料庫中獲取連線:
                            - 如果三個同時來的,一人給一個連結
                            - 如果一個一個來,有時間間隔,用一個連結就可以為三個執行緒提供服務
                                - 說不準
                                    有可能:1個連結就可以為三個執行緒提供服務
                                    有可能:2個連結就可以為三個執行緒提供服務
                                    有可能:3個連結就可以為三個執行緒提供服務
                         PS、:maxshared在使用pymysql中均無用。連結資料庫的模組:只有threadsafety>1的時候才有用

我們先來思考一個問題,為什麼要有連線池這個東西呢?不用連線池有什麼不好的地方呢?
先來看看我們使用pymysql時的常規做法:

import pymysql
from  flask import Flask

app = Flask(__name__)

@app.route('/index')
def index():
    # 連線資料庫
    conn = pymysql.connect(host="127.0.0.1",port=3306,user='root',password='123', database='pooldb',charset='utf8')
    cursor = conn.cursor()
    cursor.execute("select * from td where id=%s", [5, ])
    result = cursor.fetchall()  # 獲取資料
    cursor.close()
    conn.close()  # 關閉連結
    print(result)
    return  "執行成功"

if __name__ == '__main__':
    app.run(debug=True)

這種方式每次請求,反覆建立資料庫連線,多次連線資料庫會非常耗時
解決辦法:放在全域性/單例模式

import pymysql
from  flask import Flask
from threading import RLock

app = Flask(__name__)
CONN = pymysql.connect(host="127.0.0.1",port=3306,user='root',password='123', database='pooldb',charset='utf8')

@app.route('/index')
def index():
    with RLock:
        cursor = CONN.cursor()
        cursor.execute("select * from td where id=%s", [5, ])
        result = cursor.fetchall()  # 獲取資料
        cursor.close()
        print(result)
        return  "執行成功"
if __name__ == '__main__':
    app.run(debug=True)

把資料庫連線放在全域性這種方式,如果是單執行緒,這樣就可以,但是如果是多執行緒,就得加把鎖。這樣就成序列的了,
不支援併發。

由於上面兩種方案都不完美,所以得把方式一和方式二聯合一下(既讓減少連結次數,也能支援併發)所有了方式三,需要
匯入一個DButils模組

基於DButils實現的資料庫連線池有兩種模式:

模式一:為每一個執行緒建立一個連結(是基於本地執行緒來實現的。thread.local),每個執行緒獨立使用自己的資料庫連結,該執行緒關閉不是真正的關閉,本執行緒再次呼叫時,還是使用的最開始建立的連結,直到執行緒終止,資料庫連結才關閉

注: 模式一:如果執行緒比較多還是會建立很多連線,模式二更常用 。

from flask import Flask
app = Flask(__name__)
from DBUtils.PersistentDB import PersistentDB
import pymysql
POOL = PersistentDB(
    creator=pymysql,  # 使用連結資料庫的模組
    maxusage=None,  # 一個連結最多被重複使用的次數,None表示無限制
    setsession=[],  # 開始會話前執行的命令列表。如:["set datestyle to ...", "set time zone ..."]
    ping=0,
    # ping MySQL服務端,檢查是否服務可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
    closeable=False,
    # 如果為False時, conn.close() 實際上被忽略,供下次使用,再執行緒關閉時,才會自動關閉連結。如果為True時, conn.close()則關閉連結,那麼再次呼叫pool.connection時就會報錯,因為已經真的關閉了連線(pool.steady_connection()可以獲取一個新的連結)
    threadlocal=None,  # 本執行緒獨享值的物件,用於儲存連結物件,如果連結物件被重置
    host='127.0.0.1',
    port=3306,
    user='root',
    password='123',
    database='pooldb',
    charset='utf8'
)

@app.route('/func')
def func():
  conn = POOL.connection()
  cursor = conn.cursor()
  cursor.execute('select * from tb1')
  result = cursor.fetchall()
  cursor.close()
  conn.close() # 不是真的關閉,而是假的關閉。 conn = pymysql.connect()   conn.close()

  conn = POOL.connection()
  cursor = conn.cursor()
  cursor.execute('select * from tb1')
  result = cursor.fetchall()
  cursor.close()
  conn.close()
if __name__ == '__main__': 
	app.run(debug=True)

模式二:建立一個連結池,為所有執行緒提供連線,使用時來進行獲取,使用完畢後在放回到連線池。
    PS:假設最大連結數有10個,其實也就是一個列表,當你pop一個,人家會在append一個,連結池的所有的連結都是按照排隊的這樣的方式來連結的。連結池裡所有的連結都能重複使用,共享的, 即實現了併發,又防止了連結次數太多

import time
import pymysql
import threading
from DBUtils.PooledDB import PooledDB, SharedDBConnection
POOL = PooledDB(
    creator=pymysql,  # 使用連結資料庫的模組
    maxconnections=6,  # 連線池允許的最大連線數,0和None表示不限制連線數
    mincached=2,  # 初始化時,連結池中至少建立的空閒的連結,0表示不建立


    maxcached=5,  # 連結池中最多閒置的連結,0和None不限制
    maxshared=3,  # 連結池中最多共享的連結數量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等模組的 threadsafety都為1,所有值無論設定為多少,_maxcached永遠為0,所以永遠是所有連結都共享。
    blocking=True,  # 連線池中如果沒有可用連線後,是否阻塞等待。True,等待;False,不等待然後報錯
    maxusage=None,  # 一個連結最多被重複使用的次數,None表示無限制
    setsession=[],  # 開始會話前執行的命令列表。如:["set datestyle to ...", "set time zone ..."]
    ping=0,
    # ping MySQL服務端,檢查是否服務可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
    host='127.0.0.1',
    port=3306,
    user='root',
    password='123',
    database='pooldb',
    charset='utf8'
)


def func():
    # 檢測當前正在執行連線數的是否小於最大連結數,如果不小於則:等待或報raise TooManyConnections異常
    # 否則
    # 則優先去初始化時建立的連結中獲取連結 SteadyDBConnection。
    # 然後將SteadyDBConnection物件封裝到PooledDedicatedDBConnection中並返回。
    # 如果最開始建立的連結沒有連結,則去建立一個SteadyDBConnection物件,再封裝到PooledDedicatedDBConnection中並返回。
    # 一旦關閉連結後,連線就返回到連線池讓後續執行緒繼續使用。

    # PooledDedicatedDBConnection
    conn = POOL.connection()

    # print(th, '連結被拿走了', conn1._con)
    # print(th, '池子裡目前有', pool._idle_cache, '\r\n')

    cursor = conn.cursor()
    cursor.execute('select * from tb1')
    result = cursor.fetchall()
    conn.close()





    conn = POOL.connection()

    # print(th, '連結被拿走了', conn1._con)
    # print(th, '池子裡目前有', pool._idle_cache, '\r\n')

    cursor = conn.cursor()
    cursor.execute('select * from tb1')
    result = cursor.fetchall()
    conn.close()


func()

threading.local

threading.local:保證每個執行緒都只有自己的一份資料,在操作時不會影響別人的,即使是多執行緒,自己的值也是互相隔離的。

import threading
import time
# 本地執行緒物件
local_values = threading.local()
def func(num):

    """
    # 第一個執行緒進來,本地執行緒物件會為他建立一個
    # 第二個執行緒進來,本地執行緒物件會為他建立一個
    {
        執行緒1的唯一標識:{name:1},
        執行緒2的唯一標識:{name:2},
    }
    :param num:
    :return:
    """
    local_values.name = num # 4
    # 執行緒停下來了
    time.sleep(2)
    # 第二個執行緒: local_values.name,去local_values中根據自己的唯一標識作為key,獲取value中name對應的值
    print(local_values.name, threading.current_thread().name)


for i in range(5):
    th = threading.Thread(target=func, args=(i,), name='執行緒%s' % i)
    th.start()

列印結果:

1 執行緒1
2 執行緒2
0 執行緒0
4 執行緒4
3 執行緒3

上下文管理

a、類似於本地執行緒
            建立Local類:
            {
                執行緒或協程唯一標識: { 'stack':[request],'xxx':[session,] },
                執行緒或協程唯一標識: { 'stack':[] },
                執行緒或協程唯一標識: { 'stack':[] },
                執行緒或協程唯一標識: { 'stack':[] },
            }
        b、上下文管理的本質
            每一個執行緒都會建立一個上面那樣的結構,
            當請求進來之後,將請求相關資料新增到列表裡面[request,],以後如果使用時,就去讀取
            列表中的資料,請求完成之後,將request從列表中移除
        c、關係
            local = {
                執行緒或協程唯一標識: { 'stack':[] },
                執行緒或協程唯一標識: { 'stack':[] },
                執行緒或協程唯一標識: { 'stack':[] },
                執行緒或協程唯一標識: { 'stack':[] },
            }
            stack = {
                push
                pop
                top
            }
            存取東西時都要基於stack來做
        d、Flask和Django區別?
                - 請求相關資料傳遞的方式
                    - django:是通過傳request引數實現的
                    - Flask:基於local物件和,localstack物件來完成的
                             當請求剛進來的時候就給放進來了,完了top取值就行了,取完之後pop走就行了
                             
                    問題:多個請求過來會不會混淆
                        -答: 不會,因為,不僅是執行緒的,還是協程,每一個協程都是有唯一標識的:
                            from greenlent import getcurrentt as get_ident  #這個就是來獲取唯一標識的 

Flask的request和session設定方式比較新穎,如果沒有這種方式,那麼就只能通過引數的傳遞。

Fask是如何做的呢?

from functools import partial
from flask.globals import LocalStack, LocalProxy
 
ls = LocalStack()
 
 
class RequestContext(object):
    def __init__(self, environ):
        self.request = environ
 
 
def _lookup_req_object(name):
    top = ls.top
    if top is None:
        raise RuntimeError(ls)
    return getattr(top, name)
 
 
session = LocalProxy(partial(_lookup_req_object, 'request'))
 
ls.push(RequestContext('c1')) # 當請求進來時,放入
print(session) # 檢視函式使用
print(session) # 檢視函式使用
ls.pop() # 請求結束pop
 
 
ls.push(RequestContext('c2'))
print(session)
 
ls.push(RequestContext('c3'))
print(session)

Flask內部實現

from greenlet import getcurrent as get_ident
 
 
def release_local(local):
    local.__release_local__()
 
 
class Local(object):
    __slots__ = ('__storage__', '__ident_func__')
 
    def __init__(self):
        # self.__storage__ = {}
        # self.__ident_func__ = get_ident
        object.__setattr__(self, '__storage__', {})
        object.__setattr__(self, '__ident_func__', get_ident)
 
    def __release_local__(self):
        self.__storage__.pop(self.__ident_func__(), None)
 
    def __getattr__(self, name):
        try:
            return self.__storage__[self.__ident_func__()][name]
        except KeyError:
            raise AttributeError(name)
 
    def __setattr__(self, name, value):
        ident = self.__ident_func__()
        storage = self.__storage__
        try:
            storage[ident][name] = value
        except KeyError:
            storage[ident] = {name: value}
 
    def __delattr__(self, name):
        try:
            del self.__storage__[self.__ident_func__()][name]
        except KeyError:
            raise AttributeError(name)
 
 
class LocalStack(object):
    def __init__(self):
        self._local = Local()
 
    def __release_local__(self):
        self._local.__release_local__()
 
    def push(self, obj):
        """Pushes a new item to the stack"""
        rv = getattr(self._local, 'stack', None)
        if rv is None:
            self._local.stack = rv = []
        rv.append(obj)
        return rv
 
    def pop(self):
        """Removes the topmost item from the stack, will return the
        old value or `None` if the stack was already empty.
        """
        stack = getattr(self._local, 'stack', None)
        if stack is None:
            return None
        elif len(stack) == 1:
            release_local(self._local)
            return stack[-1]
        else:
            return stack.pop()
 
    @property
    def top(self):
        """The topmost item on the stack.  If the stack is empty,
        `None` is returned.
        """
        try:
            return self._local.stack[-1]
        except (AttributeError, IndexError):
            return None
 
 
stc = LocalStack()
 
stc.push(123)
v = stc.pop()
 
print(v)