溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在Flask框架中使用DBUtils模塊連接數據庫

發(fā)布時間:2021-03-17 16:54:32 來源:億速云 閱讀:227 作者:Leah 欄目:開發(fā)技術

本篇文章為大家展示了怎么在Flask框架中使用DBUtils模塊連接數據庫,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

Flask連接數據庫

數據庫連接池:

Django使用:django ORM(pymysql/MySqldb)

Flask/其他使用:

    -原生SQL
        -pymysql(支持python2/3)
        -MySqldb(支持python2)
    -SQLAchemy(ORM)

原生SQL

需要解決的問題:

        -不能為每個用戶創(chuàng)建一個連接
        -創(chuàng)建一定數量的連接池,如果有人來

使用DBUtils模塊

兩種使用模式:

    1 為每個線程創(chuàng)建一個連接,連接不可控,需要控制線程數
    2 創(chuàng)建指定數量的連接在連接池,當線程訪問的時候去取,如果不夠了線程排隊,直到有人釋放。平時建議使用這種!?。?/p>

模式一:

import pymysql
from DBUtils.PersistentDB import PersistentDB
POOL = PersistentDB(
  creator=pymysql, # 使用鏈接數據庫的模塊
  maxusage=None, # 一個鏈接最多被重復使用的次數,None表示無限制
  setsession=[], # 開始會話前執(zhí)行的命令列表。如:["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,如果為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'
)
def func():
  conn = POOL.connection(shareable=False)
  cursor = conn.cursor()
  cursor.execute('select * from tb1')
  result = cursor.fetchall()
  cursor.close()
  conn.close()
func()

模式二(推薦):

import time
import pymysql
import threading
from DBUtils.PooledDB import PooledDB, SharedDBConnection
POOL = PooledDB(
  creator=pymysql, # 使用鏈接數據庫的模塊
  maxconnections=6, # 連接池允許的最大連接數,0和None表示不限制連接數
  mincached=2, # 初始化時,鏈接池中至少創(chuàng)建的空閑的鏈接,0表示不創(chuàng)建
  maxcached=5, # 鏈接池中最多閑置的鏈接,0和None不限制
  maxshared=3, # 鏈接池中最多共享的鏈接數量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等模塊的 threadsafety都為1,所有值無論設置為多少,_maxcached永遠為0,所以永遠是所有鏈接都共享。
  blocking=True, # 連接池中如果沒有可用連接后,是否阻塞等待。True,等待;False,不等待然后報錯
  maxusage=None, # 一個鏈接最多被重復使用的次數,None表示無限制
  setsession=[], # 開始會話前執(zhí)行的命令列表。如:["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異常
  # 否則
  # 則優(yōu)先去初始化時創(chuàng)建的鏈接中獲取鏈接 SteadyDBConnection。
  # 然后將SteadyDBConnection對象封裝到PooledDedicatedDBConnection中并返回。
  # 如果最開始創(chuàng)建的鏈接沒有鏈接,則去創(chuàng)建一個SteadyDBConnection對象,再封裝到PooledDedicatedDBConnection中并返回。
  # 一旦關閉鏈接后,連接就返回到連接池讓后續(xù)線程繼續(xù)使用。
  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.py

from flask import Flask
from db_helper import SQLHelper
app = Flask(__name__)
@app.route("/")
def hello():
  result = SQLHelper.fetch_one('select * from xxx',[])
  print(result)
  return "Hello World"
if __name__ == '__main__':
  app.run()

DBUTILs

以下為兩種寫法:

第一種是用靜態(tài)方法裝飾器,通過直接執(zhí)行類的方法來連接使用數據庫

第二種是通過實例化對象,通過對象來調用方法執(zhí)行語句

建議使用第一種,更方便,第一種還可以在修改優(yōu)化為,將一些公共語句在摘出來使用。

import time
import pymysql
from DBUtils.PooledDB import PooledDB
POOL = PooledDB(
  creator=pymysql, # 使用鏈接數據庫的模塊
  maxconnections=6, # 連接池允許的最大連接數,0和None表示不限制連接數
  mincached=2, # 初始化時,鏈接池中至少創(chuàng)建的空閑的鏈接,0表示不創(chuàng)建
  maxcached=5, # 鏈接池中最多閑置的鏈接,0和None不限制
  maxshared=3, # 鏈接池中最多共享的鏈接數量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等模塊的 threadsafety都為1,所有值無論設置為多少,_maxcached永遠為0,所以永遠是所有鏈接都共享。
  blocking=True, # 連接池中如果沒有可用連接后,是否阻塞等待。True,等待;False,不等待然后報錯
  maxusage=None, # 一個鏈接最多被重復使用的次數,None表示無限制
  setsession=[], # 開始會話前執(zhí)行的命令列表。如:["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'
)
"""
class SQLHelper(object):
  @staticmethod
  def fetch_one(sql,args):
    conn = POOL.connection()
    cursor = conn.cursor()
    cursor.execute(sql, args)
    result = cursor.fetchone()
    conn.close()
    return result
  @staticmethod
  def fetch_all(self,sql,args):
    conn = POOL.connection()
    cursor = conn.cursor()
    cursor.execute(sql, args)
    result = cursor.fetchone()
    conn.close()
    return result
# 調用方式:
result = SQLHelper.fetch_one('select * from xxx',[])
print(result)
"""
"""
#第二種:
class SQLHelper(object):
  def __init__(self):
    self.conn = POOL.connection()
    self.cursor = self.conn.cursor()
  def close(self):
    self.cursor.close()
    self.conn.close()
  def fetch_one(self,sql, args):
    self.cursor.execute(sql, args)
    result = self.cursor.fetchone()
    self.close()
    return result
  def fetch_all(self, sql, args):
    self.cursor.execute(sql, args)
    result = self.cursor.fetchall()
    self.close()
    return result
obj = SQLHelper()
obj.fetch_one()
"""

上述內容就是怎么在Flask框架中使用DBUtils模塊連接數據庫,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI