Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中与Singleton共享声明性_基(SQLAlchemy)_Python_Sql_Singleton_Sqlalchemy - Fatal编程技术网

在Python中与Singleton共享声明性_基(SQLAlchemy)

在Python中与Singleton共享声明性_基(SQLAlchemy),python,sql,singleton,sqlalchemy,Python,Sql,Singleton,Sqlalchemy,当所有内容都在一个文件中时,我可以正常运行SQLAlchemy。我现在想把我的模型放到另一个文件中 但是,这不起作用,因为我找不到一种分享基地的方式。我尝试使用单例,但model.py中的单例为Null,并且从未在数据库中创建模式 我该怎么做才能解决这个问题 我的文件(简化版): main/main.py: from model import User from utils.utils import readConf,createSession,getBase class Worker(thr

当所有内容都在一个文件中时,我可以正常运行SQLAlchemy。我现在想把我的模型放到另一个文件中

但是,这不起作用,因为我找不到一种分享基地的方式。我尝试使用单例,但model.py中的单例为Null,并且从未在数据库中创建模式

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

我的文件(简化版):

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, *args, **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/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(), primary_key=True, nullable=False)
编辑@Lafaya

我更改了
model/\uuuuu init\uuuuuu.py
如下:

#!/usr/bin/python
Base = declarative_base()
from model import Base

class User(Base):
    etc...
然后我更改了
model/model.py
如下:

#!/usr/bin/python
Base = declarative_base()
from model import Base

class User(Base):
    etc...
现在我无法从model.py导入Base(因为它可以通过
\uuu init.py\uu
导入)。但我需要一个参考基地

Traceback (most recent call last):
  File "../main/main.py", line 12, in <module>
    from model.model import User
  File "../model/model.py", line 3, in <module>
    from model import Base
ImportError: cannot import name Base
回溯(最近一次呼叫最后一次):
文件“./main/main.py”,第12行,在
从model.model导入用户
文件“./model/model.py”,第3行,在
从模型导入库
ImportError:无法导入名称基

在模型包的
\uuuuu init\uuuuuuuuuupy
中写入
基础。然后您可以导入并使用它


Base
放入
model/\uuuu init\uuuu.py

好的,我终于将模型放入init.py了