我使用flask-restless并在我的第一次POST(来自Postman)时收到Bad Request(400)错误。如果我继续提出相同的请求,它会继续出错。但是如果我删除那个不知所措的字段,再次运行POST,得到一个肯定的响应,重新添加相同的字段,再次运行它,从那时起它就可以正常工作。
网址:/api/appraisals
请求JSON:
{
"suggested_price": 88,
"listing": {"id": 1}
}
错误回复:
{
"message": "Model does not have field 'listing'"
}
app.py:
from models.db import init_app
from controllers import api
app = Flask(__name__)
app.config.from_object('config')
init_app(app)
api.init_api(app)
来自models.db.py的:
from flask.ext.sqlalchemy import SQLAlchemy
def init_app(app):
with app.app_context():
db.init_app(app)
db.create_all()
db = SQLAlchemy()
来自controllers.api.py的:
from flask.ext.restless import APIManager
class ResourceManager(APIManager): ...
def init_api(app):
with app.app_context():
manager = ResourceManager(app, flask_sqlalchemy_db=db)
manager.add_resource(ListingResource())
manager.add_resource(AppraisalResource())
来自models.appraisal.py的:
from .db import db
from .base import BaseModel
class Appraisal(BaseModel):
__tablename__ = "appraisal"
# required fields
suggested_price = db.Column(db.Integer, nullable=False)
# optional fields
currency = db.Column(db.Unicode, default=u"USD")
# relationships
listing_id = db.Column(db.Integer, db.ForeignKey('listing.id'))
来自models.listing.py的:
from sqlalchemy.schema import UniqueConstraint
from .db import db
from .base import BaseModel
class Listing(StatusfulModel, BaseModel):
__tablename__ = "listing"
# relationships
appraisals = db.relationship(
"Appraisal",
backref=db.backref("listing", uselist=False),
uselist=True)
来自controllers.resource.appraisal.py的:
class AppraisalResource(Resource):
model_class = Appraisal
base_url = "appraisals"
allowed_methods = ["POST", "GET"]
def get_fields(self):
super_fields = super(AppraisalResource, self).get_fields()
return super_fields + [
"listing",
"listing.id"
]
答案 0 :(得分:2)
我认为解释如何解决此错误的最佳方法是在考虑这个问题时告诉你我的想法。
您将通过API进入这种情况,并且需要通过导入来了解如何来考虑逻辑。
/api/appraisals
) - 评估 您的型号:
class Appraisal(BaseModel):
__tablename__ = "appraisal"
suggested_price = db.Column(db.Integer, nullable=False)
currency = db.Column(db.Unicode, default=u"USD")
listing_id = db.Column(db.Integer, db.ForeignKey('listing.id'))
看了这个之后,你可以看到Flask期待" listing_id" - 而不是"列出"
我希望我很清楚,告诉我你是否需要任何帮助。 古德勒克!