栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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''

# 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:



    
        Todo app
    
    
        
    {% for d in data %}
  • {{ d.description }}
  • {% endfor %}

Run the program:

$ FLASK_APP=app.py FLASK_DEBUG=true flask run

结果如下:


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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/498868.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号