python - 除运行 py 文件外,无法在 python-eve 中包含模型

标签 python rest curl sqlalchemy eve

我使用 SQLAlchemy 为我的模型编写了一个 python-eve 应用程序。 当我在 run.py 文件中定义模型时,它工作得很好。 当我在另一个文件中定义表并将它们导入到 run.py 中时,服务器就会运行,但是当我尝试通过curl向其中一个资源发送请求时,我收到错误。

我的 curl 请求:

curl -i 127.0.0.1:5000/people

我收到以下错误:

o = self.data[key]()

KeyError: 'People'

我知道之前的错误了!当夏娃试图寻找不存在的东西时,它就会出现。夏娃没有找到模范人物。我不知道为什么它找不到 People 模型。

我不想将所有模型都放在 run.py 中。我想将我的表分隔在另一个文件中。

但是,如果我在 run.py 中实现模型,它就可以完美地工作,我可以发出 GET、POST、PATCH、DELETE 请求。

出于某种原因,模型必须在 run.py 中定义,并且还必须在应用初始化之前定义。

这是我的代码:

运行.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)

设置.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:PASSWORD@localhost:5432/SOMEDB'

ITEM_METHODS = ['GET', 'DELETE', 'PATCH', 'PUT']

DEBUG = True

ID_FIELD = 'id'

config.ID_FIELD = ID_FIELD

表.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类。删除run.py中的Base类,并将Base类从tables.py导入到run.py

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

如果您使用新的基类,那么您的表将不会被创建,因为这个新的基类没有从中派生的模型类。元数据将表附加在其上。

关于python - 除运行 py 文件外,无法在 python-eve 中包含模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42476681/

相关文章:

python - 如何使用 Tensorflow 向张量添加维度

python - 使用条件语句返回数据帧的子集

python - Flask Restful 添加资源参数

java - 验证多个 Controller 方法的 URL 路径

python - 在 Python 脚本中执行 curl 命令

php - 使用 php 获取谷歌搜索图像

php - 有没有等同于php的curl_getinfo的python库?

python - 导入模块,即导入另一个模块。 Python

python - 返回不断变化的变量python

java - 未找到 com.sun.jersey.core.header.FormDataContentDisposition 类的消息正文阅读器