Flask中的单例模式
1,基于文件的单例模式:
import pymysql
import threading
from DBUtils.PooledDB import PooledDB class SingletonDBPool(object):
_instance_lock = threading.Lock() def __init__(self):
self.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='123456',
database='pooldb',
charset='utf8'
) def __new__(cls, *args, **kwargs):
if not hasattr(SingletonDBPool, "_instance"):
with SingletonDBPool._instance_lock:
if not hasattr(SingletonDBPool, "_instance"):
SingletonDBPool._instance = object.__new__(cls, *args, **kwargs)
return SingletonDBPool._instance def connect(self):
return self.pool.connection()
from pool import SingletonDBPool def run():
pool = SingletonDBPool()
con = pool.connect()
# xxxxxx con.close() if __name__ == '__main__':
run()
# 单例模式:无法支持多线程情况
"""
class Singleton(object): def __init__(self):
import time
time.sleep(1) @classmethod
def instance(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance import threading def task(arg):
obj = Singleton.instance()
print(obj) for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
""" # # 单例模式:支持多线程情况
"""
import time
import threading
class Singleton(object):
_instance_lock = threading.Lock() def __init__(self):
time.sleep(1) @classmethod
def instance(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance def task(arg):
obj = Singleton.instance()
print(obj)
for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
time.sleep(20)
obj = Singleton.instance()
print(obj)
"""
基于__new__方法实现单例模式
# class Singleton(object):
# def __init__(self):
# print('init',self)
#
#
# def __new__(cls, *args, **kwargs):
# o = object.__new__(cls, *args, **kwargs)
# print('new',o)
# return o
#
# obj = Singleton()
#
# print('xxx',obj) import time
import threading
class Singleton(object):
_instance_lock = threading.Lock() def __init__(self):
pass def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = object.__new__(cls, *args, **kwargs)
return Singleton._instance obj1 = Singleton()
obj2 = Singleton()
print(obj1,obj2) # def task(arg):
# obj = Singleton()
# print(obj)
#
# for i in range(10):
# t = threading.Thread(target=task,args=[i,])
# t.start()
基于metaclass
"""
1.对象是类创建,创建对象时候类的__init__方法自动执行,对象()执行类的 __call__ 方法
2.类是type创建,创建类时候type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法) # 第0步: 执行type的 __init__ 方法【类是type的对象】
class Foo:
def __init__(self):
pass def __call__(self, *args, **kwargs):
pass # 第1步: 执行type的 __call__ 方法
# 1.1 调用 Foo类(是type的对象)的 __new__方法,用于创建对象。
# 1.2 调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。
obj = Foo()
# 第2步:执行Foodef __call__ 方法
obj()
""" """
class SingletonType(type):
def __init__(self,*args,**kwargs):
super(SingletonType,self).__init__(*args,**kwargs) def __call__(cls, *args, **kwargs):
obj = cls.__new__(cls,*args, **kwargs)
cls.__init__(obj,*args, **kwargs) # Foo.__init__(obj)
return obj class Foo(metaclass=SingletonType):
def __init__(self,name):
self.name = name
def __new__(cls, *args, **kwargs):
return object.__new__(cls, *args, **kwargs) obj = Foo('name')
"""
import threading class SingletonType(type):
_instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with SingletonType._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
return cls._instance class Foo(metaclass=SingletonType):
def __init__(self,name):
self.name = name obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)
# ######################## 基于 类方法实现 #########################
"""
import time
import threading
class Singleton(object):
_instance_lock = threading.Lock() def __init__(self):
time.sleep(1) @classmethod
def instance(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance # 使用先说明,以后用单例模式,obj = Singleton.instance()
# 示例:
# obj1 = Singleton.instance()
# obj2 = Singleton.instance()
# print(obj1,obj2)
# 错误示例
# obj1 = Singleton()
# obj2 = Singleton()
# print(obj1,obj2)
"""
# ######################### 基于__new__方式实现 #########################
"""
import time
import threading
class Singleton(object):
_instance_lock = threading.Lock() def __init__(self):
pass def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = object.__new__(cls, *args, **kwargs)
return Singleton._instance # 使用先说明,以后用单例模式,obj = Singleton()
# 示例
# obj1 = Singleton()
# obj2 = Singleton()
# print(obj1,obj2)
""" # ######################### 基于metaclass方式实现 ###################
"""
import threading class SingletonType(type):
_instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with SingletonType._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
return cls._instance class Foo(metaclass=SingletonType):
def __init__(self,name):
self.name = name obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)
""" # PS: 为了保证线程安全在内部加入锁
# 装饰器实现的单例模式
#
def wrapper(cls):
instance = {}
def inner(*args,**kwargs):
if cls not in instance:
instance[cls] = cls(*args,**kwargs)
return instance[cls]
return inner @wrapper
class Singleton(object):
def __init__(self,name,age):
self.name = name
self.age = age obj1 = Singleton('haiyan',22)
obj2 = Singleton('xx',22)
print(obj1)
print(obj2)
Flask中的单例模式的更多相关文章
- flask中的上下文_请求上下文和应用上下文
前引 在了解flask上下文管理机制之前,先来一波必知必会的知识点. 面向对象双下方法 首先,先来聊一聊面向对象中的一些特殊的双下划线方法,比如__call__.__getattr__系列.__get ...
- Objective-C中的单例模式
单例模式算是设计模式中比较简单的一种吧,设计模式不是只针对某种编程语言,在C++, Java, PHP等其他OOP语言也有设计模式,笔者初接触设计模式是通过<漫谈设计模式>了解 ...
- C# 中实现单例模式
文章目录 简介 不安全线程的单例模式 简单安全线程带锁 双重检查 - 带锁 安全初始化 安全并且懒汉式静态初始化 带泛型的懒汉式单例 异常 提高效率 总结 简介 单例模式是软件工程中广为人知的设计模式 ...
- FlASK中的endpoint问题
先贴一点有关的flask代码,时间有限,我慢慢扩充 以下是flask源码中app.py中add_url_rule的代码. 主要是view_func -- endpoint -- url 之间的对应关 ...
- 转:C++中的单例模式
C++中的单例模式 单例模式也称为单件模式.单子模式,可能是使用最广泛的设计模式.其意图是保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享.有很多地方需要这样的功能模块, ...
- 浅谈iOS中的单例模式
iOS中的单例模式 就我本身理解而言,我认为的单例:单例在整个工程中,就相当于一个全局变量,就是不论在哪里需要用到这个类的实例变量,都可以通过单例方法来取得,而且一旦你创建了一个单例类,不论你 ...
- 关于JDK中采用单例模式的类
JDK设计模式应用——单例模式(Singleton) <JDK源码分析>的分支,讲解设计模式在jdk中使用. 我们从三个方面讲述,一是:jdk源码中的设计模式:二是:讲解设计模式(UML图 ...
- java中的单例模式与doublecheck
转自: http://devbean.blog.51cto.com/448512/203501 在GoF的23种设计模式中,单例模式是比较简单的一种.然而,有时候越是简单的东西越容易出现问题.下面就单 ...
- Flask 中的 SQLAlchemy 使用教程
Flask 是一个 python web micro framework.所谓微框架,主要是 flask 简洁与轻巧,自定义程度高.相比 django 更加轻量级. 之前一直折腾 django,得益于 ...
随机推荐
- 查看SQL Server当前会话的隔离级别
查看SQL Server当前会话的隔离级别 DBCC USEROPTIONS
- 「mysql优化专题」什么是慢查询?如何通过慢查询日志优化?(10)
日志就跟人们写的日记一样,记录着过往的事情.但是人的日记是主观的(记自己想记的内容),而数据库的日志是客观的,根据记录内容分为以下好几种日志(技术文): a.错误日志:记录启动.运行或停止mysqld ...
- DotNetCore跨平台~功能测试TestHost的使用
回到目录 之前写了关于自动化测试的相关文章,包括gitlab,unittest,jenkins pipeline等,基于都是功能点的测试,当我们的框架或者业务修改之后,需要走一篇自动化测试,以此来保证 ...
- ES6之Class
ES6中的Class和JS的比起来无疑是让对象原型的写法更加清晰,更像面向对象编程的语法而已,注意一个问题ES6里面的Class的内部定义的所有方法都是不可枚举的,而且在ES6中Class不存在变量提 ...
- JavaScript的setter与getter方法
作者:http://hawkzz.com 以前在写项目过程一直都没有使用过Javascript的setter与getter方法,所以对其是一种要懂不懂的概念:今天看书看到这个知识点,还是模模糊糊的,于 ...
- Wincc的使用
1.组态项目步骤 1)启动Wincc 2)建立项目 3)选择及安装通信驱动程序 4)定义变量 5)建立和编辑过程画面 6)指定Wincc运行系统的属性 7)激活Wincc画面 8)使用变量模拟器测试过 ...
- 最全linux命令
arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS / DMI ...
- 520. Detect Capital
Given a word, you need to judge whether the usage of capitals in it is right or not. We define the ...
- iOS学习——iOS常用的存储方式
不管是在iOS还是Android开发过程中,我们都经常性地需要存储一些状态和数据,比如用户对于App的相关设置.需要在本地缓存的数据等等.根据要存储的的数据的大小.存储性质以及存储类型,在iOS和An ...
- DNS查询的工作原理
二.DNS查询的工作原理 1.DNS查询过程按两部分进行 1.名称查询从客户端计算机开始, 并传送给本机的DNS客户服务程序进行解析 2.如果不能再本机解析查询, 可根据设定的查询DN ...