python+Mysql+flask架构的在线留言板实战

在线留言板实战项目说明文档

用python操作mysql完成一个在线留言板系统

  • 1.设计留言板表
  • 2.通过python语言实现

1 项目基本功能

留言板系统主要功能:(要求使用类实现)

  • 1.显示留言板:显示留言板内容 包括ID编号、昵称、留言信息
  • 2.发布留言:可以从留言板展示页面跳转到发布留言界面
  • 3.删除留言:在留言板展示界面直接点击删除链接即可删除留言
  • 4.修改留言:在留言板展示界面点击修改链接可以转到修改留言界面

2 项目基本结构

Messag_ board/
│  Message_board.py
│  README.md
│
├─.idea
│  │  .gitignore
│  │  misc.xml
│  │  modules.xml
│  │  pymysql.iml
│  │  workspace.xml
│  │
│  └─inspectionProfiles
│          profiles_settings.xml
│          Project_Default.xml
│
└─templates
        add.html
        index.html
        update.html

3 运行环境

  • 系统:windows
  • 版本:python 3.9+
  • 其他:无

4 项目开发流程(学习用)

  1. 实现web的基本搭建 flask框架实现web的基本搭建
  • (1)安装flask框架

    pip install flask
    
  • (2)使用flask框架搭建web

  1. 创建留言板数据库
    留言板需要存储哪些数据?

    id nikename 昵称 info 留言信息 datetime 留言时间

创建表:

mysql
    create table lyb(
      id int unsigned not null auto_increment primary key,
      nikename varchar(6) not null,
      info text not null,
      date datetime not null
    )engine=innodb default charset=utf8mb4;

插入数据:

  insert into lyb values(null,"Jas","帮我买一张票","2022-01-01 11:11:11");
  1. 连接数据库并发起请求 获取请求结果
  2. 设计留言板html显示界面 显示留言板
  3. 设计留言添加功能
  • (1) 设计留言添加html界面
  • (2) 将新留言信息插入数据库
  1. 设计留言删除功能
  2. 设计留言修改功能
  • (1)设计留言修改html界面
  • (2)将修改的留言更新到mysql中

5 项目代码

Message_board.py

"""
用python操作mysql完成一个在线留言板
    1.设计在线留言板表
    2.通过python语言实现
"""
import pymysql
from flask import Flask,render_template,request
import time

app = Flask(__name__)


# 连接数据库并发起请求 获取请求结果
def model(sql):
    # 1.链接mysql数据库
    db = pymysql.connect(host='localhost',
                         user='root',
                         password='123456',
                         database='Jasmine',
                         cursorclass=pymysql.cursors.DictCursor)
    try:
        # 2.创建游标对象
        cursor = db.cursor()
        # 3.执行sql语句
        res = cursor.execute(sql)
        db.commit()  # 在执行sql语句时,注意进行提交
        # 4.提取结果
        data = cursor.fetchall()
        if data:
            return data
        else:
            return res
    except:
        db.rollback()  # 当代码出现错误时,进行回滚
    finally:
        # 6.关闭数据库连接
        db.close()


# 留言板列表 显示留言信息
@app.route("/")
def hello():
    # 1.获取所有的留言板数据
    # 2.把数据分配到模板中(html页面)
    row = model("select * from lyb")
    return render_template('index.html',data=row)


# 定义视图 显示留言添加的页面
@app.route('/add')
def add():
    return render_template('add.html')


# 定义视图函数 接收表单数据,完成数据的入库
@app.route('/insert', methods=['POST'])
def insert():
    # 1.接收表单数据
    data = request.form.to_dict()
    data['date'] = time.strftime('%Y-%m-%d %H:%M:%S')
    print(data)
    # 2.把数据添加到数据库
    sql = f'insert into lyb values(null,"{data["nikename"]}","{data["info"]}","{data["date"]}")'
    res = model(sql)
    print(res)
    # 3.成功后页面跳转到 留言列表界面
    if res:
        return '<script>alert("留言成功!");location.href="/"</script>'
    else:
        return '<script>alert("留言发布失败!");location.href="/add"</script>'


# 删除 一行留言
@app.route("/delete")
def delete():
    id = request.args.get('id')
    sql = f'delete from lyb where id={id}'
    res = model(sql)
    if res:
        return '<script>alert("删除成功!");location.href="/"</script>'
    else:
        return '<script>alert("删除失败!");location.href="/"</script>'


# 修改留言视图界面  不能修改id 即使在text文本框中修改了也没用
@app.route("/update")
def update():
    id = request.args.get('id')
    sql = f'select * from lyb where id={id}'
    res = model(sql)
    return render_template('update.html', data=res)


# 修改留言视图函数 在数据库中修改留言内容
@app.route('/modify', methods=['POST'])
def modify():
    # 1.接收表单数据
    data = request.form.to_dict()
    data['date'] = time.strftime('%Y-%m-%d %H:%M:%S')
    # 2.把数据添加到数据库
    sql = f'update lyb set nikename="{data["nikename"]}",info="{data["info"]}",date="{data["date"]}" where id={int(data["id"])}'
    res = model(sql)
    # 3.成功后页面跳转到 留言列表界面
    if res:
        return '<script>alert("修改成功!");location.href="/"</script>'
    else:
        return '<script>alert("留言修改失败!");location.href="/"</script>'


if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1', port='8080')

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>留言板列表</title>
</head>
<body>
    <center>
        <h1 style="color:dark;">留言列表</h1>
        <h3><a href="/add">发布留言</a></h3>
        <table border="1" width="800">
            <tr>
                <th>ID编号</th>
                <th>昵称</th>
                <th>留言信息</th>
                <th>留言时间</th>
                <th>删除</th>
                <th>修改</th>
            </tr>
            {% for i in data %}
            <tr>
                <td>{{i.id}}</td>
                <td>{{i.nikename}}</td>
                <td>{{i.info}}</td>
                <td>{{i.date}}</td>
                <td><a href="/delete?id={{i.id}}">删除</a></td>
                <td><a href="/update?id={{i.id}}">修改</a></td>
            </tr>
            {% endfor %}

        </table>
    </center>
</body>
</html>

add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加留言</title>
</head>
<body>
    <center>
        <h1 style="color: darkred">添加留言</h1>
        <table>
            <form action="/insert" method="post">
                <tr>
                    <td>昵称:</td>
                    <td><input type="text" name="nikename"></td>
                </tr>
                <tr>
                    <td>留言信息:</td>
                    <td><textarea name="info" id="" cols="30" rows="10"></textarea></td>
                </tr>
                <tr>
                    <td><button id="add">添加</button></td>
                </tr>
            </form>
        </table>
    </center>
</body>
</html>

update.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>修改留言</title>
</head>
<body>
    <center>
        <h1 style="color: darkred">修改留言</h1>
        <table>
            <form action="/modify" method="post">
                <tr>
                    <td>id:</td>
                    <td>
                        <textarea name="id" cols="20" rows="1">{{data[0].id}}</textarea>
                    </td>
                </tr>
                <tr>
                    <td>昵称:</td>
                    <td>
                        <textarea name="nikename" cols="20" rows="1">{{data[0].nikename}}</textarea>
                    </td>
                </tr>
                <tr>
                    <td>留言信息:</td>
                    <td>
                        <textarea name="info" cols="30" rows="10">{{data[0].info}}
                        </textarea>
                    </td>

                </tr>
                <tr>
                    <td colspan="2">
                        <button id="add">修改</button>
                    </td>
                </tr>
            </form>

        </table>
    </center>
</body>
</html>
  • 19
    点赞
  • 90
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jasmine-Lily

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值