如何解决flask_sqlalchemy无法返回所有行
当我尝试将GET请求发送到“ http:// {{MY IP}}:5000 / alldocuments”时,出现错误。我正在关注youtube视频教程,甚至github上的直接示例也无法正常工作。所有其他路线均有效,但我无法使该路线正常工作。我在SQLAlchemy的文档中找不到我的答案,但也许我只是想念它。我不知道怎么了?我正在传递带有附加数据的结果对象。
我正在youtube上观看此视频:https://www.youtube.com/watch?v=PTZiDnuC86g
这是带有教程完整代码的github: https://github.com/bradtraversy/flask_sqlalchemy_rest
我收到此错误:
<!--
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/flask/app.py",line 2309,in __call__
return self.wsgi_app(environ,start_response)
File "/usr/lib/python3/dist-packages/flask/app.py",line 2295,in wsgi_app
response = self.handle_exception(e)
File "/home/pi/.local/lib/python3.7/site-packages/flask_restful/__init__.py",line 272,in error_router
return original_handler(e)
File "/usr/lib/python3/dist-packages/flask/app.py",line 1741,in handle_exception
reraise(exc_type,exc_value,tb)
File "/usr/lib/python3/dist-packages/flask/_compat.py",line 35,in reraise
raise value
File "/usr/lib/python3/dist-packages/flask/app.py",line 2292,in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python3/dist-packages/flask/app.py",line 1815,in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/pi/.local/lib/python3.7/site-packages/flask_restful/__init__.py",line 1718,in handle_user_exception
reraise(exc_type,line 1813,in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python3/dist-packages/flask/app.py",line 1799,in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/pi/GotangoDocs/Backend/server.py",line 76,in get_documents
return jsonify(result.data)
AttributeError: 'list' object has no attribute 'data'
-->
请参阅下面的完整代码:
from flask import Flask,request,jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_restful import Resource,Api
import os
from datetime import datetime
# Init app
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
# Database
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir,'db.sqlite')
# Init db
db = SQLAlchemy(app)
# Init ma
ma = Marshmallow(app)
# --- Document Route ---
# Document Class/Model
class Document(db.Model):
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
name = db.Column(db.String(100),unique=True)
description = db.Column(db.String(200))
location = db.Column(db.String(200))
date_created = db.Column(db.DateTime,default=datetime.now)
def __init__(self,name,description,location,date_created):
self.name = name
self.description = description
self.location = location
self.date_created = date_created
# Document Schema
class DocumentSchema(ma.Schema):
class Meta:
fields = ('id','name','description','location','date_created')
# Init schema
document_schema = DocumentSchema()
documents_schema = DocumentSchema(many=True)
# Create a Document
@app.route('/document',methods=['POST'])
def add_document():
name = request.json['name']
description = request.json['description']
location = request.json['location']
new_document = Document(name,location)
db.session.add(new_document)
db.session.commit()
return document_schema.jsonify(new_document)
# Get All Documents
@app.route('/alldocuments',methods=['GET'])
def get_documents():
all_documents = Document.query.all()
result = documents_schema.dump(all_documents)
return jsonify(result.data)
# Get Single Document
@app.route('/documentById/<id>',methods=['GET'])
def get_document(id):
document = Document.query.get(id)
return document_schema.jsonify(document)
# Update a Document
@app.route('/documentById/<id>',methods=['PUT'])
def update_document(id):
document = Document.query.get(id)
name = request.json['name']
description = request.json['description']
location = request.json['location']
date_created = request.json['date_created']
document.name = name
document.description = description
document.location = location
document.date_created = date_created
db.session.commit()
return document_schema.jsonify(document)
# Delete Document
@app.route('/document/<id>',methods=['DELETE'])
def delete_document(id):
document = Document.query.get(id)
db.session.delete(document)
db.session.commit()
return document_schema.jsonify(document)
# Run Server
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0')
解决方法
第76行应为:
return jsonify(result)
代替:
return jsonify(result.data)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。