Flask系列(三)藍圖、基於DButils實現數據庫鏈接池、上下文管理

 知識點回顧

一、子類繼承父類的三種方式html

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')

二、對象經過索引設置值得三種方式python

方式1、重寫__setitem__方法mysql

class Foo(object):
    def __setitem__(self, key, value):
        print(key,value)

obj = Foo()
obj["xxx"] = 123   #給對象賦值就會去執行__setitem__方法

方式2、繼承dictsql

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)

總結:若是遇到obj[‘xxx’] = xx,django

- 重寫了__setitem__方法flask

- 繼承dictsession

三、測試__name__方法多線程

示例:併發

app1中:
    import app2
    print('app1', __name__)


app2中:
    print('app2', __name__)

如今app1是主程序,運行結果截圖

總結:

若是是在本身的模塊中運行,__name__就是__main__,若是是從別的文件中導入進來的,就不是__main__了

1、設置配置文件的幾種方式

==========方式一:============
 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不在一個模塊。就得

導入來拿。能夠不用導入,。直接導入一個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"

2、藍圖(flask中多py文件拆分都要用到藍圖)

若是代碼很是多,要進行歸類。不一樣的功能放在不一樣的文件,吧相關的視圖函數也放進去。藍圖也就是對flask的目錄結構進行分配(應用於小,中型的程序),

一、小中型:

manage.py

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)

accout.py

from 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")

order.py

from flask import Blueprint
order = Blueprint("order",__name__)

@order.route('/order')
def register():   #注意視圖函數的名字不能和藍圖對象的名字同樣
    return "order

使用藍圖時須要注意的

二、大型:

 

 

 

 3、數據庫鏈接池

flask中是沒有ORM的,若是在flask裏面鏈接數據庫有兩種方式

1:pymysql
2:SQLAlchemy
是python 操做數據庫的一個庫。可以進行 orm 映射官方文檔 sqlchemy
SQLAlchemy「採用簡單的Python語言,爲高效和高性能的數據庫訪問設計,實現了完整的企業級持久模型」。SQLAlchemy的理念是,SQL數據庫的量級和性能重要於對象集合;而對象集合的抽象又重要於表和行。

一、鏈接池原理

   - BDUtils數據庫連接池  
                - 模式一:基於threaing.local實現爲每個線程建立一個鏈接,關閉是
                  僞關閉,當前線程能夠重複
                - 模式二:鏈接池原理
                        - 能夠設置鏈接池中最大鏈接數    9
                        - 默認啓動時,鏈接池中建立鏈接  5
                        
                        - 若是有三個線程來數據庫中獲取鏈接:
                            - 若是三個同時來的,一人給一個連接
                            - 若是一個一個來,有時間間隔,用一個連接就能夠爲三個線程提供服務
                                - 說不許
                                    有可能:1個連接就能夠爲三個線程提供服務
                                    有可能:2個連接就能夠爲三個線程提供服務
                                    有可能:3個連接就能夠爲三個線程提供服務
                         PS、:maxshared在使用pymysql中均無用。連接數據庫的模塊:只有threadsafety>1的時候纔有用

二、pymysql方式實現鏈接池

方式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)

方式2、不支持併發

#!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模塊使用

方式3、因爲上面兩種方案都不完美,因此得把方式一和方式二聯合一下(既讓減小連接次數,也能支持併發)全部了方式三,須要

導入一個DButils模塊

基於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()





    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 pymysql
import threading
from DBUtils.PooledDB import PooledDB, SharedDBConnection
POOL = PooledDB(
    creator=pymysql,  # 使用連接數據庫的模塊
    maxconnections=20,  # 鏈接池容許的最大鏈接數,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='192.168.11.38',
    port=3306,
    user='root',
    passwd='apNXgF6RDitFtDQx',
    db='m2day03db',
    charset='utf8'
)


def connect():
    # 建立鏈接
    # conn = pymysql.connect(host='192.168.11.38', port=3306, user='root', passwd='apNXgF6RDitFtDQx', db='m2day03db')
    conn = POOL.connection()
    # 建立遊標
    cursor = conn.cursor(pymysql.cursors.DictCursor)

    return conn,cursor

def close(conn,cursor):
    # 關閉遊標
    cursor.close()
    # 關閉鏈接
    conn.close()

def fetch_one(sql,args):
    conn,cursor = connect()
    # 執行SQL,並返回收影響行數
    effect_row = cursor.execute(sql,args)
    result = cursor.fetchone()
    close(conn,cursor)

    return result

def fetch_all(sql,args):
    conn, cursor = connect()

    # 執行SQL,並返回收影響行數
    cursor.execute(sql,args)
    result = cursor.fetchall()

    close(conn, cursor)
    return result

def insert(sql,args):
    """
    建立數據
    :param sql: 含有佔位符的SQL
    :return:
    """
    conn, cursor = connect()

    # 執行SQL,並返回收影響行數
    effect_row = cursor.execute(sql,args)
    conn.commit()

    close(conn, cursor)

def delete(sql,args):
    """
    建立數據
    :param sql: 含有佔位符的SQL
    :return:
    """
    conn, cursor = connect()

    # 執行SQL,並返回收影響行數
    effect_row = cursor.execute(sql,args)

    conn.commit()

    close(conn, cursor)

    return effect_row

def update(sql,args):
    conn, cursor = connect()

    # 執行SQL,並返回收影響行數
    effect_row = cursor.execute(sql, args)

    conn.commit()

    close(conn, cursor)

    return effect_row
sql_help

4、本地線程

保證每一個線程都只有本身的一份數據,在操做時不會影響別人的,即便是多線程,本身的值也是互相隔離的

沒用線程以前:

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

5、上下文管理

一、原理猜測

a、相似於本地線程
            建立Local類:
            {
                線程或協程惟一標識: { 'stack':[request],'xxx':[session,] },
                線程或協程惟一標識: { 'stack':[] },
                線程或協程惟一標識: { 'stack':[] },
                線程或協程惟一標識: { 'stack':[] },
            }
        b、上下文管理的本質
            每個線程都會建立一個上面那樣的結構,
            當請求進來以後,將請求相關數據添加到列表裏面[request,],之後若是使用時,就去讀取
            列表中的數據,請求完成以後,將request從列表中移除
        c、關係
            local = 小華={
                線程或協程惟一標識: { 'stack':[] },
                線程或協程惟一標識: { 'stack':[] },
                線程或協程惟一標識: { 'stack':[] },
                線程或協程惟一標識: { 'stack':[] },
            }
            stack = 強哥 = {
                push
                pop
                top
            }
            存取東西時都要基於強哥來作
        d、最近看過一些flask源碼,flask仍是django有些區別
            - Flask和Django區別?
                - 請求相關數據傳遞的方式
                    - django:是經過傳request參數實現的
                    - Flask:基於local對象和,localstark對象來完成的
                             當請求剛進來的時候就給放進來了,完了top取值就好了,取完以後pop走就好了
                             
                    問題:多個請求過來會不會混淆
                        -答: 不會,由於,不只是線程的,仍是協程,每個協程都是有惟一標識的:
                            from greenlent import getcurrentt as get_ident  #這個就是來獲取惟一標識的 

二、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)

三、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__')
 
    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)
相關文章
相關標籤/搜索