flask中是沒有ORM的,若是在flask裏要鏈接數據庫有兩種方式python
一:pymysql
二:SQLAlchemy
是python 操做數據庫的一個庫。可以進行 orm 映射官方文檔 sqlchemy
SQLAlchemy「採用簡單的Python語言,爲高效和高性能的數據庫訪問設計,實現了完整的企業級持久模型」。SQLAlchemy的理念是,SQL數據庫的量級和性能重要於對象集合;而對象集合的抽象又重要於表和行。
- DBUtils數據庫連接池 - 模式一:基於threaing.local實現爲每個線程建立一個鏈接,關閉是僞關閉,當前線程能夠重複 - 模式二:鏈接池原理 - 能夠設置鏈接池中最大鏈接數 9 - 默認啓動時,鏈接池中建立鏈接 5 - 若是有三個線程來數據庫中獲取鏈接: - 若是三個同時來的,一人給一個連接 - 若是一個一個來,有時間間隔,用一個連接就能夠爲三個線程提供服務 - 說不許 有可能:1個連接就能夠爲三個線程提供服務 有可能:2個連接就能夠爲三個線程提供服務 有可能:3個連接就能夠爲三個線程提供服務 PS、:maxshared在使用pymysql中均無用。連接數據庫的模塊:只有threadsafety>1的時候纔有用
#!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)
這種方式每次請求,反覆建立數據庫連接,屢次連接數據庫會很是耗時mysql
這時,咱們會想到一種解決方法,就是把數據庫連接放到全局,即方式二
sql
#!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實現的數據庫鏈接池數據庫
爲每個線程建立一個連接(是基於本地線程來實現的。thread.local),每一個線程獨立使用本身的數據庫連接,該線程關閉不是真正的關閉,本線程再次調用時,仍是使用的最開始建立的連接,直到線程終止,數據庫連接才關閉。flask
#!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)
缺點:若是線程比較多,仍是會建立不少鏈接session
建立一個連接池,爲全部線程提供鏈接,使用時來進行獲取,使用完畢後在放回到鏈接池。多線程
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()
本地線程:保證每一個線程都只有本身的一份數據,在操做時不會影響別人的,即便是多線程,本身的值也是互相隔離的app
沒用線程以前ide
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 - 每一個線程進來都是打印的本身的,只有本身的才能修改, - 經過他就能保證每個線程裏面有一個數據庫連接,經過他就能建立出數據庫連接池的第一種模式 - 上下文原理 - 相似於本地線程 - 猜測:內部是否是基於本地線程作的?不是,是一個特殊的字典
#!/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)
#!/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)