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)