在python-eve中不能包含模型,除非在运行py文件中
问题描述:
我已经为我的模型编写了一个使用SQLAlchemy的python-eve应用程序。 当我在我的run.py文件中定义模型时,它完美地工作。 当我在另一个文件中定义我的表并将它们导入到run.py中时,服务器将运行,但是当我尝试通过curl向其中一个资源发送请求时,出现错误。在python-eve中不能包含模型,除非在运行py文件中
我卷曲的要求:
curl -i 127.0.0.1:5000/people
,我得到以下错误:
o = self.data[key]()
KeyError: 'People'
嗯,我知道错误从之前!当前夕试图找到不存在的东西时,它就会出现。 Eve没有找到模特人物。我不知道为什么它找不到人物模型。
我不想让我所有的模型都在run.py中。我想让我的表在另一个文件中分开。
但是,如果我在run.py中实现模型,它可以完美地工作,我可以使GET,POST,PATCH,DELETE请求。
由于某些原因,模型必须在run.py中定义,它也必须定义在应用程序初始化的上方。
那么这里是我的代码:
run.py
from sqlalchemy.ext.declarative import declarative_base
from eve import Eve
from eve_sqlalchemy import SQL
from eve_sqlalchemy.validation import ValidatorSQL
from tables import People
Base = declarative_base()
app = Eve(validator=ValidatorSQL, data=SQL)
# bind SQLAlchemy
db = app.data.driver
Base.metadata.bind = db.engine
db.Model = Base
db.create_all()
if __name__ == '__main__':
app.run(debug=True, use_reloader=False)
settings.py
from eve_sqlalchemy.decorators import registerSchema
from eve.utils import config
from tables import People
registerSchema('people')(People)
DOMAIN = {
'people': People._eve_schema['people'],
}
RESOURCE_METHODS = ['GET', 'POST']
SQLALCHEMY_DATABASE_URI = 'postgresql://USER:[email protected]:5432/SOMEDB'
ITEM_METHODS = ['GET', 'DELETE', 'PATCH', 'PUT']
DEBUG = True
ID_FIELD = 'id'
config.ID_FIELD = ID_FIELD
tables.py
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import column_property
from sqlalchemy import Column, Integer, String, DateTime, func
Base = declarative_base()
class CommonColumns(Base):
__abstract__ = True
_created = Column(DateTime, default=func.now())
_updated = Column(DateTime, default=func.now(), onupdate=func.now())
_etag = Column(String(40))
class People(CommonColumns):
__tablename__ = 'people'
_id = Column(Integer, primary_key=True, autoincrement=True)
firstname = Column(String(80))
lastname = Column(String(120))
fullname = column_property(firstname + " " + lastname)
@classmethod
def from_tuple(cls, data):
"""Helper method to populate the db"""
return cls(firstname=data[0], lastname=data[1])
答
问题是使用了两个不同的Base
类。取下基类,它从里面tables.py
run.py
和进口基类run.py
#run.py
from tables import Base, People #import Base
Base = declarative_base() #remove this line
如果你使用一个新的基类,则不会创建您的表,因为这种新的基本类没有模型类衍生。元数据保留附加的表格。
谢谢,工作! – mbijou