Flask初学小项目:使用表单与重定向以及Flask-SQLAl

2019-06-26  本文已影响0人  字节的风

1.项目概述

这是一个类似于缺德诈骗网购预约的项目:

空白网站 输入信息后 感谢用户并保存

2.Talk is cheap, show him the code!

该导入的包导入一下。

from flask import Flask, render_template, session, redirect, url_for, flash

from flask_wtf import Form
from wtforms import SubmitField, StringField, IntegerField, RadioField
from wtforms.validators import DataRequired, NumberRange

from flask_bootstrap import Bootstrap

import os
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

创建app本身,初始化Bootstrap和SQLAlchemy、Flask-Migrate

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)

# Warning: 把SECRET_KEY写在源代码中的习惯很不好!
app.config['SECRET_KEY'] = '**********'

app.config['SQLALCHEMY_DATABASE_URI'] =\
    'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app=app)
migrate = Migrate(app, db)

bootstrap = Bootstrap(app)

创建模型~

class Costumer(db.Model):
    __tablename__ = 'costumers'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    address = db.Column(db.String(256), unique=True)
    phone_number = db.Column(db.BigInteger, unique=True)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

    def __repr__(self):
        return '<User id:{} name:{} address:{} phone_number:{} role_id:{}>'.format(
            self.id, self.name, self.address, self.phone_number, self.role_id
        )

class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    users = db.relationship('Costumer', backref='role')

    def __repr__(self):
        return '<Role id:{} name:{} users{}>'.format(self.id, self.name, self.users)

表单也要有气质~

# 表单
class BuyForm(Form):
    name = StringField('收货人姓名', validators=[DataRequired()])
    address = StringField('收货地址', validators=[DataRequired()])
    phone_number = IntegerField('电话号码', 
                                validators=[DataRequired(),
                                            NumberRange(
                                                        min=10000000, 
                                                        max=99999999999999, 
                                                        message='不是正常的电话号码'
                                                        )
                                            ]
                                )
    role = RadioField(
        label='您是?',
        choices=(
            (3, '普通顾客'),
            (1, '铂金VIP'),
            (2, '白金VIP'),
        ),
        coerce=int
    )
    submit = SubmitField('预约')

接下来进入终端,执行:

export FLASK_APP=main.py
flask shell
>>> from main import db, Role
>>> black_gold_vip = Role(name='铂金VIP')
>>> white_gold_vip = Role(name='白金VIP')
>>> normal_costumer = Role(name='普通顾客')
>>> db.session.add.all([black_gold_vip, white_gold_vip, normal_costumer])
>>> db.session.commit()
>>> exit()

开始搭建视图函数

@app.route('/')
def start():
    return redirect(url_for('index'))

@app.route('/index', methods=['GET', 'POST'])
def index():
    # 初始化
    costumers = Costumer.query.all()
    form = BuyForm()

    # 如果有顾客购买产品
    if form.validate_on_submit():
        # 在购买名单中保存
        data_dict = {
            'name': form.name.data,
            'address': form.address.data,
            'phone_number': form.phone_number.data,
            'role': Role.query.filter_by(id=form.role.data).first(),
        }
        db.session.add(Costumer(**data_dict))
        db.session.commit()
        # 保存名字用于结束页
        session['name'] = form.name.data
        # 清空表单
        form.name.data = None
        form.address.data = None
        form.phone_number.data = None
        # 跳转至结束页
        flash('感谢您的预约!请时刻关注您的电话,到时付款。:)')
        return redirect(url_for('index'))
        
    # 返回新网页
    return render_template('index.html', form=form, num=len(costumers))

@app.errorhandler(404)
def error_404(e):
    return redirect(url_for('index'))

@app.errorhandler(500)
def error_500(e):
    return render_template('500.html')

这个网页应用的基本实现都是在index()中的。

接下来是使用HTML这门编程语言超文本标记语言联合Bootstrap和Jinja2创造前端的屎诗级奇迹

index.html

{% extends "bootstrap/base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}抢购 - 预约{% endblock %}

{% block content %}
<div class="container">
    {% for message in get_flashed_messages() %}
    <div class="alert alert-warning">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        {{ message }}
    </div>
    {% endfor %}
    <h1>现在购买!已经有{{ num }}人预约了!</h1>
    {{ wtf.quick_form(form) }}
</div>
{% endblock %}

象征着Bug来临的,程序猿的噩梦:500.html

{% extends "bootstrap/base.html" %}

{% block title %}500{% endblock %}

{% block content %}
<div class="container">
    <h1>出现了一点问题,已经报告完毕,我们将稍后修复。</h1>
    <h2>错误报告中不包含您的隐私信息,请您放心!</h2>
</div>
{% endblock %}
<!--- 但愿一辈子看不着 --->

The end.

print('码字不易,加个关注,收录一下,点个喜欢!')
my_heart = True

踩蛋

今天终于会操作SQL了~感觉棒棒哒~

上一篇下一篇

猜你喜欢

热点阅读