2

使用 Flask、Graphene 并遇到问题。考虑以下。

模型项目.model.site:

from project import db
from project.models import user
from datetime import datetime

class Site(db.Model):
    __tablename__ = 'sites'
    id = db.Column(db.Integer(), primary_key=True)
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    name = db.Column(db.String(50))
    desc = db.Column(db.Text())
    location_lon = db.Column(db.String(50))
    location_lat = db.Column(db.String(50))
    creation_date = db.Column(db.DateTime(), default=datetime.utcnow())
    users = db.relationship(
        user,
        backref=db.backref('users',
                        uselist=True,
                        cascade='delete,all'))

模型架构 (project.schemas.site_schema)

from graphene_sqlalchemy import SQLAlchemyObjectType
from project.models import site as site_model
import graphene

class SiteAttributes:
    owner_id = graphene.ID(description="Site owners user.id")
    name = graphene.String(description="Site Name")
    desc = graphene.String(description="Site description")
    location_lon = graphene.String(description="Site Longitude")
    location_lat = graphene.String(description="Site Latitude")
    creation_date = graphene.DateTime(description="Site Creation Date")

class Site(SQLAlchemyObjectType, SiteAttributes):
    """Site node."""
    class Meta:
        model = site_model
        interfaces = (graphene.relay.Node,)

最后是我计划通过它公开 GraphQL api (project.schemas.schema) 的主要模式

from graphene_sqlalchemy import SQLAlchemyConnectionField
import graphene
from project.schemas import site_schema, trade_schema, user_schema

class Query(graphene.ObjectType):
    """Query objects for GraphQL API."""

    node = graphene.relay.Node.Field()
    user = graphene.relay.Node.Field(user_schema.User)
    userList = SQLAlchemyConnectionField(user_schema.User)
    site = graphene.relay.Node.Field(site_schema.Site)
    siteList = SQLAlchemyConnectionField(site_schema.Site)
    trade = graphene.relay.Node.Field(trade_schema.Trade)
    tradeList = SQLAlchemyConnectionField(trade_schema.Trade)


schema = graphene.Schema(query=Query)

如果我在启动时加载模型,一切都很好。发生迁移,应用程序运行良好。如果我通过模式加载模型,但应用程序失败并显示以下消息:

AssertionError: You need to pass a valid SQLAlchemy Model in Site.Meta, received "<module 'project.models.site' from '/vagrant/src/project/models/site.py'>".

我用 flask_sqlalchemy 初始化了 SQLAlchemy。这让我想知道创建的模型是否不被视为有效的 SQLAlchemy 模型?还是我在这里犯了一个我没有看到的基本错误。我假设是后者。

4

2 回答 2

4

根据错误消息,似乎project.models.site(在第二个片段中用 导入from project.models import site as site_model)是一个 Python 模块,而不是一个子类db.Model或类似的。您是否可能是要导入Site(大写)而不是site

于 2018-10-27T23:54:07.450 回答
1

因此,将包固定到课程最终使我朝着正确的方向前进。事实证明,这个问题比那个更深。获得它的唯一方法是阅读隐藏的异常。

首先,我确保加载的是实际模型而不是模块。非常感谢@jwodder

最后,这个https://github.com/graphql-python/graphene-sqlalchemy/issues/121最终为我指明了正确的方向。通过检查实际的异常消息,我找到了解决方案

于 2018-10-28T01:38:09.353 回答