flask flask-sqlalchemy sqlit3

2024-01-09 22:27:54

这次是数据库使用,拒绝花哨主打就是一个简单

pip install flask-sqlalchemy

调用数据库现在配置里边设置下然后绑上APP后,定义数据结构类.下面是我认为最简单的数据库增删查改结构。


from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
##定义数据结构类
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    def __repr__(self):
        return '<User %r>' % self.username
## 如果没有表要创建表,有的话则无改动
with app.app_context():
    db.create_all()
##查询数据
@app.route("/sql")
def find_all_users():
    users = User.query.all()
    print(users)
    return render_template("sql.html", users=users)
##查询一个数据
@app.route("/get/<int:get_id>")
def get_by_id(get_id):
    get_user = User.query.get(get_id)  # User.query.filter_by(id=get_id).first()
    return "编号:{0},用戶名:{1},邮箱:{2}".format(get_user.id, get_user.username, get_user.email)
##增加数据
@app.route("/add/<username>")
def add_user(username):
    new_user = User()
    new_user.username = username
    new_user.email = username + "@qq.com"
    db.session.add(new_user)
    db.session.commit()
    return redirect("/")
##删除数据
@app.route("/delete/<int:del_id>")
def delete_by_id(del_id):
    del_user = User.query.filter_by(id=del_id).first()
    if del_user is not None:
        db.session.delete(del_user)
        db.session.commit()
    return redirect("/")

@app.route("/update", methods=["GET", "POST"])
def update():
    if request.method == "POST":
        user_id = request.form.get("id")
        new_username = request.form.get("username")
        new_email = request.form.get("email")
        user = User.query.get(user_id)
        if user:
            user.username = new_username
            user.email = new_email
            db.session.commit()
        return redirect(url_for("update"))
    users = User.query.all()
    return render_template("update.html", users=users)

sql.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table border="1">
    <tr>
        <th>编号</th>
        <th>用户名</th>
        <th>邮箱</th>
        <th>操作</th>
    </tr>
    {% for u in users %}
        <tr>
            <td>{{ u.id }}</td>
            <td>{{ u.username }}</td>
            <td>{{ u.email }}</td>
            <td>
                <a href="delete/{{ u.id }}">删除</a>
            </td>
        </tr>
    {% endfor %}
</table>

update.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Update User</title>
</head>
<body>
    <table border="1">
        <tr>
            <th>编号</th>
            <th>用户名</th>
            <th>邮箱</th>
        </tr>
        {% for u in users %}
            <tr>
                <td>{{ u.id }}</td>
                <td>{{ u.username }}</td>
                <td>{{ u.email }}</td>
            </tr>
        {% endfor %}
    </table>
    <h2>更新用户信息</h2>
    <form action="/update" method="post">
        <label for="id">用户ID:</label><br>
        <input type="text" id="id" name="id" required><br>
        <label for="username">新用户名:</label><br>
        <input type="text" id="username" name="username" required><br>
        <label for="email">新邮箱:</label><br>
        <input type="email" id="email" name="email" required><br>
        <input type="submit" value="更新">
    </form>
</body>
</html>

补充内容数据迁移

安装

pip install flask-migrate

app 里边进行注册和绑定

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
from flask_migrate import Migrate
migrate =Migrate(app,db)

类似GIT的版本控制。流程为初始化(只执行一次)==》构建迁移脚本=》迁移

flask db init
flask db migrate
flask db upgrade

这脚本自动构建的时候经常自己出错需要打开排查

文章来源:https://blog.csdn.net/gaoke11240/article/details/135431101
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。