2017-02-27 78 views
1

我已經爲我的模型編寫了一個使用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]) 

回答

1

問題是使用了兩個不同的Base類。取下基類,它從裏面tables.pyrun.py和進口基類run.py

#run.py 
from tables import Base, People #import Base 
Base = declarative_base()   #remove this line 

如果你使用一個新的基類,則不會創建您的表,因爲這種新的基本類沒有模型類衍生。元數據保留附加的表格。

+0

謝謝,工作! – mbijou