Flask框架单例模式实现方法详解
本文实例讲述了Flask框架单例模式实现方法。分享给大家供大家参考,具体如下:
单例模式:
程序运行时只能生成一个实例,避免对同一资源产生冲突的访问请求。
Django admin.py下的admin.site.register() , site就是使用文件导入方式的单例模式
创建到单例模式4种方式:
- 1.文件导入
- 2. 类方式
- 3.基于__new__方式实现
- 4.基于metaclass方式实现
1.文件导入:
in single.py
class Singleton():
def __init__(self):
pass
site = Singleton()
类似:
import time 第一次已经把导入的time模块,放入内存
import time 第二次内存已有就不导入了
in app.py
from single.py import site #第一次导入,实例化site对象并放入内存
in views.py
from single.py import site #第二次导入,直接从内存拿。
2.类方式:
缺点:改变了单例的创建方式
obj = Singleton.instance()
# 单例模式:无法支持多线程情况
import time
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 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
3.基于__new__方式实现:
单例创建方式:
obj1 = Singleton() obj2 = Singleton()
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
4.基于metaclass方式实现
基于metaclass方式实现的原理:
- 1.对象是类创建,创建对象时候类的__init__方法自动执行,对象()执行类的 __call__ 方法
- 2.类是type创建,创建类时候type的__init__方法自动执行,类() 执行type的 __call__方法
单例创建方式:
obj1 = Foo() obj2 = Foo()
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):
pass
希望本文所述对大家基于flask框架的Python程序设计有所帮助。
相关文章
python网络爬虫之模拟登录 自动获取cookie值 验证码识别的具体实现
有时,我们需要爬取一些基于个人用户的用户信息(需要登陆后才可以查看)就要进行模拟登陆,因为验证码往往是作为登陆请求中的请求参数被使用,就需要识别验证码2021-09-09
Python 正则表达式(?=...)和(?<=...)符号的使用
本文主要介绍Python 正则表达式(?=...)和(?<=...)符号的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2024-05-05


最新评论