您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中与Singleton共享Declarative_Base(SQLAlchemy)

5b51 2022/1/14 8:21:15 python 字数 6146 阅读 473 来源 www.jb51.cc/python

当一切都在一个文件中时,我可以正常运行SQLAlchemy.我现在想把我的模型放到另一个文件中.但是,这不起作用,因为我找不到共享基础的方法.我尝试使用Singleton但它在model.py中是Null,并且从不在数据库中创建模式.我该怎么做才能解决这个问题?我的文件(简化版): - /main/__init__.py - /main/m

概述

当一切都在一个文件中时,我可以正常运行sqlAlchemy.我现在想把我的模型放到另一个文件中.

但是,这不起作用,因为我找不到共享基础的方法.我尝试使用Singleton但它在model.py中是Null,并且从不在数据库中创建模式.

我该怎么做才能解决这个问题?

我的文件(简化版):

     - /main/__init__.py
     - /main/main.py
     - /utils/__init__.py
     - /utils/utils.py
     - /model/__init__.py
     - /model/model.py

main / main.py:

from model import User
from utils.utils import readConf,createSession,getBase

class Worker(threading.Thread): 

    def __init__(self,queue,session):
        self.__queue = queue
        threading.Thread.__init__(self)
        self._stopevent = threading.Event( )

    def run(self):
        session.merge(User(queue.get()))
        session.commit()


class Collector(threading.Thread):

    def __init__(self,nom = ''):
        threading.Thread.__init__(self)
        self.nom = nom
        self._stopevent = threading.Event( )


    def run(self):
        while not self._stopevent.isSet():
            queue.put("Name")

if __name__ == '__main__':
    conf = readConf("file.")
    session = createSession(conf)
    queue = Queue.Queue(0)      
    Worker(queue,session).start()
    Collector("Start").start()

utils的/ utils.py

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import MetaData

def createSession(conf):
    schema = conf['bdd']['type'] + '://' + conf['bdd']['user'] + ':' + conf['bdd']['password'] + '@' + conf['bdd']['host'] + '/' + conf['bdd']['db']
    engine = create_engine(schema,echo=True)

    b = getBase("Utils")
    b.set_base(declarative_base())

    Base = b.get_base()    
    Base.Metadata.create_all(engine)     

    Session = sessionmaker(bind=engine)
    session = Session()
    return session

class getBase(object):
    __single = None # the one,true Singleton
    __base = None
    __text = None
    __base = None

    def __new__(cls,*args,**kwargs):
        # Check to see if a __single exists already for this class
        # Compare class types instead of just looking for None so
        # that subclasses will create their own __single objects
        if cls != type(cls.__single):
            cls.__single = object.__new__(cls,**kwargs)
            __base = declarative_base()

        return cls.__single

    def __init__(self,name=None):
        self.name = name

    def get_base(self):
        return self.__base


    def set_base(self,value):
        self.__base = value

模型/ model.py

from utils.utils import getBase

b = getBase("model")
b.set_base(declarative_base())
Base = b.get_base()

class User(Base):
    __tablename__ = 'users'

    def __init__(self,name):
        self.screen_name = name

    name_id = Column(Integer,primary_key=True,autoincrement=True)
    screen_name = Column(BigInteger(),nullable=False)

编辑@Lafaya

我更改了model / __ init__.py:

#!/usr/bin/python
Base = declarative_base()

然后我改变了model / model.py:

from model import Base

class User(Base):
    etc...

现在我无法从model.py导入Base(因为它由__init.py__导入).但我需要参考Base!

Traceback (most recent call last):
  File "../main/main.py",line 12,in 
  

Jut将Base放在model / __ init__.py中.

总结

以上是编程之家为你收集整理的在Python中与Singleton共享Declarative_Base(SQLAlchemy)全部内容,希望文章能够帮你解决在Python中与Singleton共享Declarative_Base(SQLAlchemy)所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶