flask_sqlalchemy не может вернуть все строки

#python #flask #sqlalchemy #flask-sqlalchemy

#python #flask #sqlalchemy #flask-sqlalchemy

Вопрос:

Когда я пытаюсь отправить GET-запрос на ‘http://{{МОЙ 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 272, in error_router
    return original_handler(e)
  File "/usr/lib/python3/dist-packages/flask/app.py", line 1718, in handle_user_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 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, description, 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')
  

Комментарии:

1. Попробуйте: return jsonify(result) вместо return jsonify(result.data) в строке 76

Ответ №1:

Строка 76 должна быть:

 return jsonify(result)
  

вместо:

 return jsonify(result.data)