Flask框架单例模式实现方法详解

yipeiwu_com6年前Python基础

本文实例讲述了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序列化与反序列化pickle用法实例

这篇文章主要介绍了Python序列化与反序列化pickle用法实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 要将Python对象...

python解决方案:WindowsError: [Error 2]

使用Python的rename()函数重命名文件时出现问题,提示 WindowsError: [Error 2] 错误,最初代码如下: def renameFile(filename...

pandas 空的dataframe 插入列名的示例

如下所示: colum = ['性别','年龄','M','样本类型'] + muta_list + ['B'] data1 = pd.DataFrame(columns=colum...

详解python uiautomator2 watcher的使用方法

该方是基于uiautomator2如下版本进行验证的: PS C:\windows\system32> pip show uiautomator2 Name: uiautoma...

手把手教你Python yLab的绘制折线图的画法

手把手教你Python yLab的绘制折线图的画法

Python的可视化工具有很多,数不胜数,各有优劣。本文就对其中的pylab进行介绍。之所以介绍这一款,是因为它和Matlab的强烈相似度,如果你使用过Matlab,那么相信pylab你...