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

yipeiwu_com5年前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 数值区间处理_对interval 库的快速入门详解

使用 Python 进行数据处理的时候,常常会遇到判断一个数是否在一个区间内的操作。我们可以使用 if else 进行判断,但是,既然使用了 Python,那我们当然是想找一下有没有现成...

50行Python代码实现视频中物体颜色识别和跟踪(必须以红色为例)

50行Python代码实现视频中物体颜色识别和跟踪(必须以红色为例)

目前计算机视觉(CV)与自然语言处理(NLP)及语音识别并列为人工智能三大热点方向,而计算机视觉中的对象检测(objectdetection)应用非常广泛,比如自动驾驶、视频监控、工业质...

Python:Scrapy框架中Item Pipeline组件使用详解

Item Pipeline简介 Item管道的主要责任是负责处理有蜘蛛从网页中抽取的Item,他的主要任务是清晰、验证和存储数据。 当页面被蜘蛛解析后,将被发送到Item管道,并经过几个...

numpy.linspace 生成等差数组的方法

numpy.linspace 生成等差数组的方法

如下所示: numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) start:...

Python smallseg分词用法实例分析

本文实例讲述了Python smallseg分词用法。分享给大家供大家参考。具体分析如下: #encoding=utf-8 #import psyco #psyco.full()...