Flask简单实例-1

# py

from flask import Flask, render_template, request, url_for, redirect
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config.from_object('setting')

db = SQLAlchemy(app=app)


''' 创建表 '''
# 分类表
class Cate(db.Model):
    id = db.Column(db.Integer, primary_key=True, comment='商品分类ID')
    cate_name = db.Column(db.String(30), nullable=False, comment='商品分类名称')

    goods = db.relationship('Goods', backref='one_cate')        # 虚拟字段

# 商品表
class Goods(db.Model):
    id = db.Column(db.Integer, primary_key=True, comment='商品ID')
    goods_name = db.Column(db.String(30), nullable=False, comment='商品名称')
    goods_tag = db.Column(db.String(30), nullable=False, comment='商品标签')
    cate_id = db.Column(db.Integer, db.ForeignKey(Cate.id), comment='外键')


# 首页
@app.route('/')
def index():
    goods = Goods.query.order_by(Goods.id.desc()).all()
    return render_template('index.html', goods=goods)


# 添加商品分类
# 方法一
@app.route('/add_cate', methods=['GET','POST'])
def add_cate():
    if request.method == 'POST':
        cate_name = request.form.get('cate_name')
        new_cate = Cate(cate_name=cate_name)
        db.session.add(new_cate)
        db.session.commit()
    return render_template('add_cate.html')

# 方法二(请求一次添加一次)
# @app.route('/add_cate')
# def add_cate():
#     new_cate1 = Cate(cate_name='女装')
#     new_cate2 = Cate(cate_name='男装')
#     db.session.add_all([new_cate1, new_cate2])
#     db.session.commit()
#     return '添加商品分类成功'


# 所有商品分类
@app.route('/all_cates')
def all_cates():
    cates = Cate.query.all()
    return render_template('all_cates.html', cates=cates)


# 添加商品到分类下
@app.route('/add_goods', methods=['GET','POST'])
def add_goods():
    cate_id = request.args.get('cate_id')
    if request.method == 'POST':
        goods_name = request.form.get('goods_name')
        goods_tag = request.form.get('goods_tag')
        new_goods = Goods(goods_name=goods_name, goods_tag=goods_tag, cate_id=cate_id)
        db.session.add(new_goods)
        db.session.commit()
    return render_template('add_goods.html')


# 所有商品
@app.route('/all_goods')
def all_goods():
    goodss = Goods.query.order_by(Goods.id.desc()).all()
    return render_template('all_goods.html', goodss=goodss)


# 删除商品
@app.route('/delete_goods')
def delete_goods():
    goods_id = request.args.get('goods_id')
    one_good = Goods.query.get(goods_id)
    db.session.delete(one_good)
    db.session.commit()
    return redirect(url_for('index'))


if __name__ == '__main__':

    # db.drop_all()
    # db.create_all()

    app.run()
{# setting.html #}

DEBUG = True                # 开启调试模式
SECRET_KEY = "abc"       # 随机输入字符串
# SQLALCHEMY_DATABASE_URI = 链接的数据库类型+使用的驱动://用户名:密码@数据库地址:端口/数据库名称?数据库编码
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/exam1?charset=utf8' # 连接数据库
# SQLALCHEMY_ECHO = True      # 在控制面板显示
SQLALCHEMY_TRACK_MODIFICATIONS = False
{# base.html #}

{% block top %}
    <a href="{{ url_for('index') }}">首页</a>
    <a href="{{ url_for('add_cate') }}">添加分类</a>
    <a href="{{ url_for('all_cates') }}">所有分类</a>
    <a href="{{ url_for('all_goods') }}">所有商品</a>
    <hr>
{% endblock top %}

{% block content %}

{% endblock content %}
{# index.html #}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    {% extends 'base.html' %}

    {% block content %}
        <table border="1" cellspacing="0">
            <tr>
                <td>商品ID</td>
                <td>商品名称</td>
                <td>标签</td>
                <td>分类</td>
                <td>操作</td>
            </tr>
            {% for i in goods %}
            <tr>
                <td>{{ i.id }}</td>
                <td>{{ i.goods_name }}</td>
                <td>{{ i.goods_tag }}</td>
                <td>{{ i.one_cate.cate_name }}</td>
                <td><a href="{{ url_for('delete_goods',goods_id=i.id) }}">删除</a></td>
            </tr>
            {% endfor %}
        </table>
    {% endblock content %}
</body>
</html>
{# add_cate.html #}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加分类</title>
</head>
<body>
    {% extends 'base.html' %}

    {% block content %}
        <form action="" method="post">
            添加分类:<input type="text" name="cate_name" value=""><br>
            <input type="submit" value="确认添加">
        </form>
    {% endblock content %}
</body>
</html>
{# add_goods.html #}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加商品</title>
</head>
<body>
    {% extends 'base.html' %}

    {% block content %}
        <form action="" method="post">
            添加商品:<input type="text" name="goods_name" value=""><br>
            添加标签:<input type="text" name="goods_tag" value=""><br>
            <input type="submit" value="确认添加">
        </form>
    {% endblock content %}
</body>
</html>
{# all_cates.html #}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>所有分类</title>
</head>
<body>
    {% extends 'base.html' %}

    {% block content %}
        {% for cate in cates %}
            {{ cate.cate_name }} |
            <a href="{{ url_for('add_goods', cate_id=cate.id) }}">添加{{ cate.cate_name }}下的商品</a> <br>
        {% endfor %}
    {% endblock content %}
</body>
</html>
{# all_goods.html #}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>所有商品</title>
</head>
<body>
    {% extends 'base.html' %}

    {% block content %}
        {% for goods in goodss %}
            {{ goods.id }}——{{ goods.goods_name }}——{{ goods.goods_tag }}——{{ goods.one_cate.cate_name }}
            | <a href="{{ url_for('delete_goods', goods_id=goods.id) }}">删除</a>
            <br>
        {% endfor %}
    {% endblock content %}
</body>
</html>

相关文章: