嘿伙计们为什么我的代码无效。我忘记了大部分关于响应标题和如何使用它的东西,我很想弄清楚何时使用dict和tuple等。
from flask import Flask, jsonify, json, request, abort
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_pyfile('Config.py')
db = SQLAlchemy(app)
response = {}
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 Todo.query.all()])
@app.route('/todo/<int:todo_ID>', methods = ['GET'])
def get(todo_ID):
todo = Todo.query.get(todo_ID)
response
response['todo_ID']= todo.todo_ID
response['UserID'] = todo.UserID
response['details'] = todo.details
response.status_code = 200
response.headers['location'] = '/todo/{}'.format(todo.todo_ID)
return response
运行此代码时,我收到以下错误。
File "/home/muba/PycharmProjects/Work/Flaskapp.py", line 43, in get
response.status_code = 200
AttributeError: 'dict' object has no attribute 'status_code'
127.0.0.1 - - [01/Mar/2017 21:29:27] "GET /todo/1 HTTP/1.1" 500 -
有人可以告诉我什么是错的,并指出我的某种教程。我唯一可以理解的是,我在顶部的响应对象由于某种原因不能使用status_code。
答案 0 :(得分:0)
假设您正在寻找以JSON格式返回echo $rand;
对象;下面是使用JSON对象和额外标头构建响应的简化示例。
<强> app.py 强>
todo
卷曲响应:
from flask import Flask, make_response
import json
app = Flask(__name__)
@app.route("/", methods=['GET'])
def index():
todo = {'todo_ID': 1, 'UserID': 2, 'details': 'test'}
r = make_response((json.dumps(todo),
200,
{'Content-Type': 'application/json',
'location': '/todo/{}'.format(todo['todo_ID'])}))
return r
if __name__ == "__main__":
app.run(debug=True)