我正在尝试使用python + flask-restful创建我的第一个API,并且在调用自定义端点时出现错误。
例如,我有下面的代码:
from app import db, app
from app import manager
from datetime import datetime
from flask import jsonify
class Climate(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime)
rainfall = db.Column(db.Integer)
temperature = db.Column(db.Integer)
def predict():
predictValue = Climate.query.filter_by(date=datetime.now().date())
return predictValue
db.create_all()
manager.create_api(Climate, methods=['POST', 'GET', 'PUT', 'DELETE'])
当我开始运行run.py并执行GET请求-> http://localhost:8080/api/climate时,它将返回以下内容:
{
"num_results": 2,
"objects": [
{
"date": "2018-10-07T00:00:00",
"id": 1,
"rainfall": 100,
"temperature": 15
},
{
"date": "2018-07-10T00:00:00",
"id": 2,
"rainfall": 200,
"temperature": 20
}
],
"page": 1,
"total_pages": 1
}
没关系。但是我想做一个自定义的端点。例如,如果我调用http://localhost:8080/api/climate/predict,我想调用Climate类中的predict()方法,以仅返回绑定请求当天的一项,但是当我执行此请求时,它仅返回
{}
是否要这样做?谢谢。
答案 0 :(得分:0)
已解决。
# endpoint to predict
@app.route("/climate/predict", methods=["GET"])
def climate():
climate = Climate.query.filter_by(date=datetime.now().date()).first()
if climate is not None:
return jsonify(serializeClimate(climate))
else:
abort(404)
所有代码在github上:https://github.com/danielnicolay321/ParetoTest/blob/master/crud.py