Flask 入門-(四)數(shù)據(jù)庫(kù)使用

前言


測(cè)試環(huán)境


工程實(shí)現(xiàn)

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>添加學(xué)生信息</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>學(xué)生信息表</caption>
            <thead>
                <tr>
                    <th>姓名</th>
                    <th>學(xué)號(hào)</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>

運(yùn)行結(jié)果:


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容