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

结果如下:
请添加图片描述


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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值