FLASK RESTful API使用GET获取特定的id并使用Python返回201

时间:2016-11-30 08:37:37

标签: python rest flask

我正在尝试使用GET方法获取todo_ID。我仍然是使用sqlalchemy的新手,我尝试过的大多数事情告诉我sqlalchemy不使用它们。此外,有人可以告诉我如何使用HEAD,我希望我的方法返回http状态,我有点尝试使用它们并导入渲染模板,但当我尝试使用它们时它说它不知道它们是什么。

这是我尝试查看教程并进行更改

from flask import Flask, jsonify,json, request, render_template, abort
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_pyfile('Config.py')
db = SQLAlchemy(app)

class JsonModel(object):  # Class for making objects JSON serializable
    def as_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

class User(db.Model, JsonModel):  # Class which is a model for the User table in the database
    User_ID = db.Column(db.Integer, primary_key = True)
    FirstName = db.Column(db.String(20))
    LastName = db.Column(db.String(20))

    def __init__(self,User_ID,FirstName, LastName):
        self.User_ID = User_ID
        self.FirstName = FirstName
        self.LastName = LastName

class Todo(db.Model, JsonModel):  # Class which is a model for the Todo table in the database
    todo_ID = db.Column(db.Integer, primary_key = True)
    UserID = db.Column(db.Integer, db.ForeignKey("user.User_ID"))
    details = db.Column(db.String(30))

    def __init__(self, UserID, details):
        self.UserID = UserID
        self.details = details

@app.route('/todo', methods = ['GET'])  # Uses GET method to return all information in the database.
def index():
    return json.dumps([u.as_dict() for u in User.query.all()+Todo.query.all()]), 201

@app.route('/todo/<int:todo_ID>', methods = ['GET'])
def get(todo_ID):
    query = Todo.query.get()
    return {'todo': [dict(zip(tuple(query.keys()), i)) for i in query.cursor if i[1] == todo_ID]}


@app.before_first_request #Creates everything before the first request.
def startup():
    db.create_all()

if __name__ == '__main__':
    app.run()

我最近的尝试是:

@app.route('/todo/<int:todo_ID>', methods = ['GET'])
def get(todo_ID):
    query = Todo.query("select * from Todo")
    return {'todo': [dict(zip(tuple(query.keys()), i)) for i in query.cursor if i[1] == todo_ID]}

我得到的错误就是这个。

query = Todo.query("select * from Todo")
TypeError: 'BaseQuery' object is not callable
127.0.0.1 - - [30/Nov/2016 21:15:28] "GET /todo/1 HTTP/1.1" 500 -

2 个答案:

答案 0 :(得分:0)

不确定我是否理解您的问题,如果您打算将json输出作为响应返回并且您想要控制状态代码,那么您可以 使用jsonify

from flask import jsonify

@app.route('/todo/<int:todo_ID>', methods = ['GET'])
def get(todo_ID):
    query = Todo.query("select * from Todo")
    response = {'todo': [dict(zip(tuple(query.keys()), i)) for i in query.cursor if i[1] == todo_ID]}
    response = jsonify(response)
    response.status_code = 201
    return response 

答案 1 :(得分:0)

如果您想通过主键查询Todo并且只返回一个记录,则可以使用:

from flask import jsonify

@app.route('/todo/<int:todo_ID>', methods = ['GET'])
def get(todo_ID):
    response = {}
    todo = Todo.query.get(todo_ID)
    response['id'] = todo.id
    response['user_id'] = todo.UserID
    response['details'] = todo.details
    response['status_code'] = 201
    return jsonify(response)

或者您可以使用Marshmallow为每个型号配置序列化程序,以便它可以自动为您序列化。