匿名留言板

发布于:2023-01-19 ⋅ 阅读:(446) ⋅ 点赞:(0)

初衷

1.网上有很多类似的成品 比如 告白岛
2.提升自己 没写过前后端交互
3.有点闲

技术

前端

HTML
JavaScript

后端

Python
Flask框架

数据库

MySQL

效果截图

主页面

在这里插入图片描述

查询页面

在这里插入图片描述

添加页面

在这里插入图片描述

代码

app.py

import sql_add_find

from flask import *

app = Flask(__name__)

sql = sql_add_find.mess_sql()


@app.route('/')
def hello_world():  # put application's code here
    sql.addvisit(request.remote_addr)
    return render_template("main.html")

#添加
@app.route('/add', methods=["POST"])
def add():
    name = str(request.form.get("name"))
    word = str(request.form.get("word"))
    return {"message": sql.add(name, word)}

#查询
@app.route('/find', methods=["POST"])
def find():
    name = str(request.form.get("name"))
    l = sql.find(name)
    res = "<h1>{0}</h1>".format(name)
    res += '''<meta name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes" />'''

    m = 'OK'
    if l == 'e':
        m = "e"
        return {"message": m, "res": res}
    for i in l:
        res += "<br> <h3>{0}</h3> <h5>{1}</h5>".format(i[0], i[1])
    res += "<br> <p>共{0}条</p>".format(len(l))
    res += "<input type=\"button\" value=\"返回\" οnclick=\"location.reload();\">"
    return {"message": m, "res": res}

#关于
@app.route('/help',methods=['POST'])
def helpfun():
    return render_template('help.html')

#运行
app.run(host='0.0.0.0',
        port=80,
        threaded=True
        )

sql_add_find/init.py

import pymysql
import datetime


class mess_sql:
    def __init__(self):
        self.word_max = 500
        self.connect = pymysql.connect(host='',#数据库地址
                                       user='root',#用户名
                                       password='',#密码
                                       db='Message',
                                       charset='gbk') 
        self.cur = self.connect.cursor()

    '''
        对一个人名添加一句话
    input:
        name:名字
        word:话
    output:
        str结果
           'word too long':超过了长度
           or 'e':连接服务器出错
           or 'OK':成功
    '''

    def add(self, name, word):
        if len(word) > self.word_max:
            return 'word too long'
        try:
            a = eval(name)
            return 'is num'
        except:
            pass
        try:
            find_name_in_table = "select name from name_list where name='{0}'".format(name)
            print("find_name_in_table",find_name_in_table)
            self.cur.execute(find_name_in_table)
            res = self.cur.fetchall()
            if len(res) == 0:
                add_name_to_table = "CREATE TABLE Message.{0}  (\
          `                  time` datetime(0) NULL,\
          `                  word` varchar({1}) NULL\
                             );".format(name, self.word_max)
                self.cur.execute(add_name_to_table)
                self.connect.commit()

                add_name_to_list = "insert into name_list values ('{0}')".format(name)
                self.cur.execute(add_name_to_list)
                self.connect.commit()
            addtext = "insert into {0} values ('{1}','{2}');".format(name, datetime.datetime.now(), word)
            print('addtext',addtext)
            self.cur.execute(addtext)
            self.connect.commit()
            return 'OK'
        except Exception as e:
            print(e)
            return 'e'

    '''
        查找指定人名
    input:
        name:人名
    output:
        list:记录
        or e:异常
    '''

    def find(self, name):
        res = []
        try:
            find_name_in_table = "select name from name_list where name='{0}'".format(name)
            self.cur.execute(find_name_in_table)
            res = self.cur.fetchall()

            if len(res) == 0:
                return []

            find_sql_str = "select * from {0}".format(name)
            self.cur.execute(find_sql_str)
            res = self.cur.fetchall()
            #for i in res:
            #    print(i[0], i[1])
            return res
        except Exception as e:
            print(e)
            return 'e'

    def addvisit(self,ip):
        add_visit_fun = "insert into visit values ('{0}','{1}')".format(datetime.datetime.now(),ip)
        try:
            self.cur.execute(add_visit_fun)
            self.connect.commit()
            return 'OK'
        except Exception as e:
            return e

templates/help.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>匿名留言馆</title>
</head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes" />

<body>
<ul>
<li>
  <h1>为什么写</h1>
  <ul>
    <li>
      <h3> 网上有很多类似的成品 比如 <a href="http://app.szxingzhihuo.com/island.html"
                        target="_blank" rel="noopener noreferrer">告白岛</a> </h3>
    </li>
    <li>
      <h3>提升自己 没写过前后端交互</h3>
    </li>
    <li>
      <h3>有点闲(跑)</h3>
    </li>
  </ul>
</li>
<li>
  <h1>用了什么</h1>
  <ul>
    <li>
      <h3>前端:html js</h3>
      <a href="https://www.runoob.com/html/html-tutorial.html">html 学习链接</a>
      <br>
    <a href="https://www.runoob.com/js/js-tutorial.html"> js 学习链接 </a> </li>
    <li>
      <h3>后端:python flask框架</h3>
      <a href="https://www.runoob.com/python3/python3-tutorial.html">Python 学习链接</a> </li>
    <li>
      <h3>数据库:MySQL</h3>
      <a href="https://www.runoob.com/mysql/mysql-tutorial.html">MySQL 学习链接</a> </li>
  </ul>
</li>
<li>
  <h1>了解更多</h1>
  <ul>
    <li>
      <h3> <a href="https://blog.csdn.net/m0_72416569/article/details/125827629">我在 CSDN 的一篇文章</a> </h3>
    </li>
    <li>
      <h3> 微信号 zjxyyds0307<img src="img\vx.jpg" alt="二维码加载失败" width="500" height="500"/></h3>
    </li>
  </ul>
</li>
</ul>
<input type="button" value="返回" onclick="location.reload();">
</body>
</html>

templates/main.html

<html>
<meta name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes" />
<title>
    匿名留言岛
</title>
<!--引入jQuery包用于使用ajax-->
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

姓名<input type="text" id="name" name="name" placeholder="姓名">
<br>要说的话<br>
<textarea style="width:300px;height:100px;" name="word" id="word" placeholder="要说的话"></textarea>
<br>
<!--创建button按钮,点击则激发submit()事件-->
<button onclick="add();">提交一份留言</button>
<button onclick="find();">查询留言</button>
<button onclick="help()">关于</button>

<script>
    function help() {  
        $.ajax({
            url : "help",
            type : "POST",
            success: function (result) {
                document.write(result)
            }
        });
    }
    function cansend(com){
        if($("#name").val().length==0){
            alert("名字不能留空");
            return false;
        }
        if($("#name").val().length >10){
            alert("名字太长");
            return false;
        }
        if(com==0){
            if($("#word").val().length >500){
                alert("要说的话太长");
                return false;
            }
            if($("#word").val().length==0){
                alert("要说的话不能留空");
                return false;
            }
        }
        return true;
    }
    function add(){
        if(!cansend(0)){
            return;
        }
        $.ajax({
            url: "add",
            type: "POST",
            data: { "name": $("#name").val() , "word": $("#word").val()},
            success: function (result) {
                if(result.message == 'is num'){
                    alert("名称只能为数字加字母或者字母 插入失败");
                }else if (result.message != "OK") {
                    alert("添加失败 请检查用户名或者网络");
                } else {
                    alert("添加成功");
                    
                    document.getElementById("word").value = "";
                }
            }
        });
    }
    function find() {
        if(!cansend(1)){
            return;
        }
        $.ajax({
            url: "find",
            type: "POST",
            data: { "name": $("#name").val() },
            success: function (result) {
                if (result.message != "OK") {
                    alert("查询失败");
                } else {
                    document.write(result.res);
                }
            }
        });
    }

</script>

</html>

项目结构

E:.
│  app.py
│
├─.idea
│  │  .gitignore
│  │  Message Board.iml
│  │  misc.xml
│  │  modules.xml
│  │  sqldialects.xml
│  │  workspace.xml
│  │
│  └─inspectionProfiles
│          profiles_settings.xml
│
├─img
│      vx.jpg
│
├─sql_add_find
│  │  __init__.py
│  │
│  └─__pycache__
│          __init__.cpython-38.pyc
│
├─static
├─templates
│  │  help.html
│  │  main.html
│  │  vx.jpg
│  │
│  └─img
│          vx.jpg
│
└─__pycache__
        app.cpython-38.pyc

数据库结构

namelist 用于记录添加过的名字

在这里插入图片描述

visit 存储访问记录

在这里插入图片描述

zjx表 存储了给zjx的留言和时间

在这里插入图片描述

不足

微信二维码加载不出

我在静态网页里可以打开它 但是服务器不可以

不够美观

没有用到什么css 界面有点丑

前端返回值

我不到为什么有时候前端返回空值 是值(0,‘’)

数据量

如果数据量增多 可能服务器内存容易不够 因为返回的值是直接存到了res并且没有做其他判断 直接写进去的 这个行为很不好

屎山见笑了xdm

前端小白 轻喷


网站公告

今日签到

点亮在社区的每一天
去签到