【发布时间】:2019-01-29 00:01:10
【问题描述】:
圣诞节前我正在学习一些教程,现在我正在尝试从我离开的地方继续学习。 尝试通过构建一些简单的 API 端点来自学 REST。我的困惑来自于我找不到我正在使用的教程,而且似乎有几种不同的方法可以解决这个问题。所以现在我不确定正确的方法是什么。 该代码适用于返回数据库中的所有客户,现在我想根据他们的 Id 返回一个特定的客户
好的,这就是我所拥有的......
我有一个 app.py,它定义了这样的资源:
api.add_resource(CustomerResource, '/Customer')
我有一个models.py,它定义了这样的客户类:
ma = Marshmallow()
db = SQLAlchemy()
class Customer(db.Model):
__tablename__ = 'customers'
__table_args__ = {"schema":"business"}
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False)
status = db.Column(db.Integer, nullable=False)
class CustomerSchema(ma.Schema):
id = fields.Integer()
name = fields.String(required=True)
status = fields.Integer(required=True)
我有 customer.py 将客户类定义为:
customers_schema = CustomerSchema(many=True)
customer_schema = CustomerSchema()
class CustomerResource(Resource):
def get(self):
customers = Customer.query.all()
customers = customers_schema.dump(customers)
return {'status': 'success', 'data': customers}, 200
我尝试过使用 request.args,但我不认为这是正确的方法,因为它会变得不支持。
因此,以上所有内容都适用于 GET 成功返回所有客户。但现在我希望能够使用 GET http://127.0.0.1:5000/api/Customer/10 并返回客户 ID = 10 的详细信息
我不确定是否需要定义新资源,或者是否可以修改现有 CustomerResource 以测试参数是否存在。
任何指导表示赞赏...
【问题讨论】:
标签: python-3.x rest get flask-sqlalchemy marshmallow