一、數據庫連接池
flask中是沒有ORM的,如果在flask里要連接數據庫有兩種方式
一:pymysql
二:SQLAlchemy
是python 操作數據庫的一個庫。能夠進行 orm 映射官方文檔 sqlchemy
SQLAlchemy“采用簡單的Python語言,為高效和高性能的數據庫訪問設計,實現了完整的企業級持久模型”。SQLAlchemy的理念是,SQL數據庫的量級和性能重要於對象集合;而對象集合的抽象又重要於表和行。
1.鏈接池原理
- DBUtils數據庫鏈接池 - 模式一:基於threaing.local實現為每一個線程創建一個連接,關閉是偽關閉,當前線程可以重復 - 模式二:連接池原理 - 可以設置連接池中最大連接數 9 - 默認啟動時,連接池中創建連接 5 - 如果有三個線程來數據庫中獲取連接: - 如果三個同時來的,一人給一個鏈接 - 如果一個一個來,有時間間隔,用一個鏈接就可以為三個線程提供服務 - 說不准 有可能:1個鏈接就可以為三個線程提供服務 有可能:2個鏈接就可以為三個線程提供服務 有可能:3個鏈接就可以為三個線程提供服務 PS、:maxshared在使用pymysql中均無用。鏈接數據庫的模塊:只有threadsafety>1的時候才有用
2.不使用連接池鏈接數據庫
方式一:每次操作都要鏈接數據庫,鏈接次數過多
#!usr/bin/env python # -*- coding:utf-8 -*- 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)
這種方式每次請求,反復創建數據庫鏈接,多次鏈接數據庫會非常耗時
這時,我們會想到一種解決方法,就是把數據庫鏈接放到全局,即方式二
方式二:不支持並發
#!usr/bin/env python # -*- coding:utf-8 -*- 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實現的數據庫連接池
3.基於DButils實現的數據庫連接池
模式一
為每一個線程創建一個鏈接(是基於本地線程來實現的。thread.local),每個線程獨立使用自己的數據庫鏈接,該線程關閉不是真正的關閉,本線程再次調用時,還是使用的最開始創建的鏈接,直到線程終止,數據庫鏈接才關閉。
#!usr/bin/env python # -*- coding:utf-8 -*- 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() func()
二、本地線程
本地線程:保證每個線程都只有自己的一份數據,在操作時不會影響別人的,即使是多線程,自己的值也是互相隔離的
沒用線程之前
import threading import time class Foo(object): def __init__(self): self.name = None local_values = Foo() def func(num): time.sleep(2) local_values.name = num 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 0 線程0 2 線程2 3 線程3 4 線程4
用了本地線程之后
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
三、上下文管理
flask的request和session設置方式比較新穎,如果沒有這種方式,那么就只能通過參數的傳遞。
flask是如何做的呢?
- 本地線程:是Flask自己創建的一個線程(猜想:內部是不是基於本地線程做的?) vals = threading.local() def task(arg): vals.name = num - 每個線程進來都是打印的自己的,只有自己的才能修改, - 通過他就能保證每一個線程里面有一個數據庫鏈接,通過他就能創建出數據庫鏈接池的第一種模式 - 上下文原理 - 類似於本地線程 - 猜想:內部是不是基於本地線程做的?不是,是一個特殊的字典
1. 上下文原理
#!/usr/bin/env python # -*- coding:utf-8 -*- 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)
2. Flask內部實現
#!/usr/bin/env python # -*- coding:utf-8 -*- from greenlet import getcurrent as get_ident def release_local(local): local.__release_local__() class Local(object): __slots__ = ('__storage__', '__ident_func__') # __slots__的作用是用tuple定義允許綁定的屬性名稱 def __init__(self): # self.__storage__ = {} # self.__ident_func__ = get_ident 等價於下面兩句,之所以這樣,是因為如果直接按這種方式設置,通過.會自動調用__setattr___,而在下面的__setattr__中
又要獲取__storage__等方法的值,這樣會會形成遞歸,所以采用這張設置方法
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)