Flask-SQLAlchemy выдает пустой список db.session.query(Class).all(). Как исправить?
Ребята, гугл не помогает. Элементарное. Есть база данных. Подключаем ее. Хотим извлечь все элементы. А выдает пустой список. Почему так происходит? Как исправить?
from flask import Flask, jsonify, render_template
from flask_sqlalchemy import SQLAlchemy
import random
app = Flask(__name__)
##Connect to Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cafes.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
db.init_app(app)
##Cafe TABLE Configuration
class Cafe(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(250), unique=True, nullable=False)
map_url = db.Column(db.String(500), nullable=False)
img_url = db.Column(db.String(500), nullable=False)
location = db.Column(db.String(250), nullable=False)
seats = db.Column(db.String(250), nullable=False)
has_toilet = db.Column(db.Boolean, nullable=False)
has_wifi = db.Column(db.Boolean, nullable=False)
has_sockets = db.Column(db.Boolean, nullable=False)
can_take_calls = db.Column(db.Boolean, nullable=False)
coffee_price = db.Column(db.String(250), nullable=True)
def to_dict(self):
# Method 1.
dictionary = {}
# Loop through each column in the data record
for column in self.__table__.columns:
# Create a new dictionary entry;
# where the key is the name of the column
# and the value is the value of the column
dictionary[column.name] = getattr(self, column.name)
return dictionary
# Method 2. Altenatively use Dictionary Comprehension to do the same thing.
# return {column.name: getattr(self, column.name) for column in self.__table__.columns}
@app.route("/all")
def get_all_cafes():
cafes = db.session.query(Cafe).all()
print(cafes)
# This uses a List Comprehension but you could also split it into 3 lines.
return jsonify(cafes=[cafe.to_dict() for cafe in cafes])
if __name__ == '__main__':
app.run(debug=True)

