flask数据库操作(flask_sqlalchemy)

Posted 月疯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask数据库操作(flask_sqlalchemy)相关的知识,希望对你有一定的参考价值。

from flask import Flask,request,render_template
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    username = db.Column(db.String(32),unique=True,nullable=False)
    password = db.Column(db.String(32),nullable=False)

if os.path.exists(os.path.join(os.path.dirname(__file__),'test.db')):
    db.create_all()


@app.route('/')
def hello_word():
    users = User.query.all()
    return render_template('index.html',users = users)

@app.route('/add_user',methods=['GET','POST'])
def add_user():
    if request.method == 'GET':
        return render_template('add_user.html')
    elif request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        user = User()
        user.username = username
        user.password = password

    try:
        db.session.add(user)
        db.session.commit()
        return '添加成功'
    except Exception:
        return '添加失败'

@app.route('/delete_user/<int:userid>')
def delete_user(userid):
    user = User.query.get(userid)
    try:
        db.session.delete(user)
        db.session.commit()
        return '删除成功'
    except Exception:
        return '删除失败'


if __name__ == '__main__':
    app.run()

 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户展示</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</head>
<body>
<table class="table table-striped">
<tr>
    <th>用户名</th>
    <th>密码</th>
    <th>删除操作</th>
</tr>
    % for user in users %
    <tr>
        <td>
           user.username 
        </td>
        <td>
           user.password 
        </td>
        <td><a href=" url_for('delete_user',userid = user.id) ">删除</a></td>
    </tr>
    % endfor %
</table>


</body>
</html>

add_user.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加用户</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</head>
<body>
<form action="add_user" method="post">
    <div class="form-group">
        <label for="username">用户名</label>
        <input type="text" name="username" id="username" class="form-control">
    </div>
    <div class="form-group">
        <label for="password">密码</label>
        <input type="password" name="password" id="password" class="form-control">
    </div>

        <input type="submit" name="提交" class="btn btn-default">

</form>

</body>
</html>

 

 

以上是关于flask数据库操作(flask_sqlalchemy)的主要内容,如果未能解决你的问题,请参考以下文章

那些年我们学Flask-SQLAlchemy,实现数据库操作,分页等功能

Flask数据库操作

3天掌握Flask开发项目系列博客之二,操作数据库

Flask中对MySQL的基本操作

使用Flask-SQLALchemy操作MySQL数据库

Flask数据库基本操作-SQLAlchemy