Flask 入门-(四)数据库使用

前言


测试环境


工程实现

app.py

from flask import Flask, render_template, url_for, redirect, flash, get_flashed_messages
from flask_bootstrap import Bootstrap
from wtforms import StringField,BooleanField, IntegerField, FloatField, SubmitField, RadioField
from wtforms.validators import DataRequired, Length
from flask_wtf import FlaskForm
from flask_sqlalchemy import SQLAlchemy
import click


app = Flask(__name__)
app.config['SECRET_KEY'] = 'hello-flask'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
bootstrap = Bootstrap(app)
db = SQLAlchemy(app=app)

# Database
class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))
    number_id = db.Column(db.String(9), unique=True)
    age = db.Column(db.Integer())
    height = db.Column(db.Integer())
    weight = db.Column(db.Float())
    gender = db.Column(db.String())


@app.cli.command()
@click.option('--drop', is_flag=True, help='Create after drop.')
def initdb(drop: bool):
    if drop:
        db.drop_all()
    db.create_all()
    click.echo('Initialized database')


# Form
class StudentForm(FlaskForm):
    name = StringField(label='Name', validators=[DataRequired(), Length(1, 30)])
    number_id = StringField(label='ID', validators=[DataRequired(), Length(9, 9)])
    age = StringField(label='Age', validators=[DataRequired()])
    gender = RadioField(label='Gender', validators=[DataRequired()], choices=['male', 'female'])
    height = IntegerField(label='Height', validators=[DataRequired()])
    weight = FloatField(label='Weight', validators=[DataRequired()])
    sumbit = SubmitField(label='submit', render_kw={"id": "btn_submit"})


@app.route('/', methods=['GET', 'POST'])
def index():
    form = StudentForm()
    if form.validate_on_submit():
        # get info by Form
        name = form.name.data
        number_id = form.number_id.data
        age = form.age.data
        gender = form.gender.data
        height = form.height.data
        weight = form.weight.data

        # check the number_id
        stu = Student.query.filter_by(number_id=number_id).first()
        if stu:
            flash('number_id={} has exist, please check!'.format(number_id))
        else:
            # create student
            stu = Student(name=name, number_id=number_id, age=age, gender=gender, height=height, weight=weight)
            db.session.add(stu)
            db.session.commit()
    students = Student.query.all()
    return render_template('index.html', form=form, students=students)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>flask_database</title>

    {{ bootstrap.load_css() }}
    {% from 'bootstrap/form.html' import render_form  %}
</head>
<body>
    <main class="container">
        <div class="row text-center">
            <h2>添加学生信息</h2>
        </div>
        <div class="row">
            <div class="col-md-5">
                {{ render_form(form=form, form_type="basic") }}
            </div>
        </div>
        <br> <br>
        {% for msg in get_flashed_messages()  %}
            <div class="alert alert-info">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                {{msg}}
            </div>
        {% endfor %}
        <table class="table table-bordered table-striped">
            <caption>学生信息表</caption>
            <thead>
                <tr>
                    <th>姓名</th>
                    <th>学号</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>身高(cm)</th>
                    <th>体重(kg)</th>
                </tr>
            </thead>
            <tbody>
                {% for stu in students  %}
                    <tr>
                        <td>{{ stu.name }}</td>
                        <td>{{ stu.number_id }}</td>
                        <td>{{ stu.age }}</td>
                        <td>{{ stu.gender }}</td>
                        <td>{{ stu.height }}</td>
                        <td>{{ stu.weight }}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    </main>
    {{ bootstrap.load_js() }}
</body>
</html>

运行结果:


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容