flask flask-sqlalchemy sqlit3

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

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 '' % 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/")
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/")
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/")
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>

你可能感兴趣的:(flask,python,后端)