开发者

Issue with DB Creation with Pyramid and SQLite

I'm building the Pyramid wiki from this tutorial.

Everything works fine, except when try to create a folder for my models instead of having them in the file models.py in the main folder.

I created a models folder, added a 开发者_如何学Python__init__.py file to it, and a Page file with the content:

from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Text

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Page(Base):
    """ The SQLAlchemy declarative model class for a Page object. """
    __tablename__ = 'pages'
    id = Column(Integer, primary_key=True)
    name = Column(Text, unique=True)
    data = Column(Text)

    def __init__(self, name, data):
       self.name = name
       self.data = data`

This doesn't work - I get a "can't find table named pages" error. This is my models.py file:

import transaction

from sqlalchemy.exc import IntegrityError

from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Text

from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from zope.sqlalchemy import ZopeTransactionExtension 

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

Base = declarative_base()

from test.models.Page import Page

Now if I replace the last line with this, everything works:

class Page(Base):
    """ The SQLAlchemy declarative model class for a Page object. """
    __tablename__ = 'pages'
    id = Column(Integer, primary_key=True)
    name = Column(Text, unique=True)
    data = Column(Text)

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

What am I doing wrong?


In your models.py file, you'll notice the initialize_sql function. This function calls the `Base.metadata.create_all()" function, which effectively creates all the tables for the objects that were defined using that Base object.

However, when you switched the Page class definition into the new file, you have created a new Base object. Since the Page class inherits from this new Base object, the Base object over in the models.py file never recognizes that the class definition even exists. Therefore, the Base object that is actually used to create the SQL tables appears to be empty, and therefore doesn't try to create the SQL table. This results in your "can't find table" error message.

To fix this, rather than creating a new Base object in your models/__init__.py file, have that file import Base from mypackage/__init__.py, and use that Base object as the superclass for Page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜