Build a CRUD App with SQLAlchemy - Implementing Reads: The “R“ in CRUD

How to implement the read operations?
Querying the database to return data-backend views, replacing our data with “real” data coming from our database.


# app.py file
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://username@localhost:5432/todoapp'
db = SQLAlchemy(app)

# Model
class Todo(db.Model):
    __tablename__ = 'todos'
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(), nullable=False)

	# useful to debug
    def __repr__(self):
        return f'<Todo {self.id} {self.description}>'

# Ensure the tables are created for all the models that we've created and they haven't been created.
db.create_all()

# Controller
@app.route('/')
def index():
    return render_template('index.html', data=Todo.query.all())


Create the db in your terminal:

$ createdb todoapp

Add value to the database:

$ psql todoapp
$ INSERT INTO todos (description) VALUES ('Do a thing 1');
$ INSERT INTO todos (description) VALUES ('Do a thing 2');
$ INSERT INTO todos (description) VALUES ('Do a thing 3');

In the templates folder, create the index.html file:

<!-- View -->
<!DOCTYPE html>
<html>
    <head>
        <title>Todo app</title>
    </head>
    <body>
        <ul>
            {% for d in data %}
                <li>
                    {{ d.description }}
                </li>
            {% endfor %}
        </ul>
    </body>
</html>

Run the program:

$ FLASK_APP=app.py FLASK_DEBUG=true flask run

结果如下:
Build a CRUD App with SQLAlchemy - Implementing Reads: The “R“ in CRUD


只有在数据库里,添加新的内容,网页就会显示最新结果。

上一篇:3年 CRUD 成为外包扫地僧,就凭一份性能优化小册面试字节完美入职架构岗


下一篇:PreparedStatement实现CRUD操作