微信咨询

微信咨询

13610*910*9

服务热线 7*24小时

电话咨询

python+flask+mysql 实现简单留言板功能

iamdu2019-12-28 23:27:26 浏览: 629636

python文件代码编写

from flask import Flask,render_template,request,jsonify
import requests,json,os,time,pymysql,datetime


app = Flask(__name__)


# 数据库配置
mysql_config={
'host':'localhost',
'port':3306,
'user':'root',
'password':'tan11300',
'db':'myblog',
}


@app.route('/bbs', methods=['POST'])


def bbs2():
        # 创建连接
        connection = pymysql.connect(**mysql_config)

        
        data = json.loads(request.form.get('data'))
        action = data['action']

        if action == 1:
                ##########################增加数据
                try:
                        with connection.cursor() as cursor:
                                #读取HTML页面数据
                                now = datetime.datetime.now()
                                data = json.loads(request.form.get('data'))
                                name = data['name']
                                nr = data['nr']
                                # 执行sql语句,插入记录
                                sql = 'INSERT INTO message (name, body, timestamp) VALUES (%s, %s, %s)'
                                cursor.execute(sql, (name, nr, now))
                        # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
                        connection.commit()

                        return jsonify({"success": 200, "msg": "提交成功"})

                finally:
                        connection.close()
        
        elif action == 2:
                #######################删除数据
                try:
                        with connection.cursor() as cursor:
                                id = data['id']
                                sql = 'DELETE FROM message where `id` like (%s) '
                                cursor.execute(sql, (id))
                        # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
                        connection.commit()

                        return jsonify({"success": 200, "msg": "删除成功"})

                finally:
                        connection.close() 

        else:  
                ########################修改数据
                try:
                        with connection.cursor() as cursor:
                                #读取HTML页面数据
                                id = data['id']
                                name = data['name']
                                nr = data['nr']
                                sql = 'UPDATE message SET name = %s ,body = %s  where `id` like %s '
                                cursor.execute(sql, (name,nr,id))
                        # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
                        connection.commit()
                        return jsonify({"success": 200, "msg": "删除成功"})

                finally:
                        connection.close() 





#留言板
@app.route('/bbs', methods=['GET'])
def bbs():


        db = pymysql.connect(**mysql_config)
        # 使用 cursor() 方法创建一个游标对象 cursor
        cursor = db.cursor()

        sql = "select * from message order by id desc;"
        cursor.execute(sql)
        res1 = cursor.fetchall()
        # print (res)
        return render_template('bbs_index.html',res1=res1)


if __name__ == '__main__':
    app.run(debug=True)  #FLASK开启调试模式,使程序修改即时生效

 

HTML模板文件编写

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>留言板</title>
<link rel="stylesheet" href="../static/layui/css/layui.css">	
<link rel="stylesheet" href="../static/style.css">
<script src="../static/jquery-3.4.1.min.js"></script>		
<script src="../static/layui/layui.all.js"></script>	
</head>

<body>
	<div style="width: 1200px; margin: 100px auto;">
<form class="layui-form"> 

  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">名字</label>
    <div class="layui-input-block">
      <input type="text" name="title" required  lay-verify="required" placeholder="请输入名字" autocomplete="off" class="layui-input name">
    </div>
  </div>

  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">内容</label>
    <div class="layui-input-block">
      <textarea placeholder="" class="layui-textarea nr"></textarea>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-input-block">
      <div class="layui-btn fybtn" lay-submit lay-filter="*">提交留言</div>
      <button type="reset" class="layui-btn layui-btn-primary clearbtn">清空内容</button>
    </div>
  </div>
  <!-- 更多表单结构排版请移步文档左侧【页面元素-表单】一项阅览 -->
</form>

<!-- 留言列表STAT-->
<div class="bbs_list">
     <ul>

{% for i in res1 %}
     <li class="li_{{ i[0] }}">
<div class="bbs_name"><span><b class="num">{{ i[0] }}</b>.&nbsp;&nbsp;<em>{{ i[1] }}</em></span><i>{{ i[3] }}</i><b class="info">[<a class="del" onclick="delete_order({{ i[0] }})"">删除</a>]&nbsp;&nbsp;&nbsp;&nbsp;[<a class="update">修改</a>]</b></div>
<div class="bbs_nr">{{ i[2] }}</div>
     </li>     
{% endfor %}   

     </ul>

</div>
<!-- 留言列表END-->


<!-- 弹出修改框-->
<div id="renew" style="display: none;">
<form class="layui-form"> 

  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">名字</label>
    <div class="layui-input-block" style="width: 300px; margin-top: 30px;">
      <input type="text" name="title" required  lay-verify="required" placeholder="请输入名字" autocomplete="off" class="layui-input uname">
    </div>
  </div>

  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">内容</label>
    <div class="layui-input-block" style="width: 300px; margin-top: 30px;">
      <textarea placeholder="" class="layui-textarea unr"></textarea>
    </div>
  </div>

</form>

</div>



<script src="layui.js"></script>
<script>
layui.use('form', function(){
  var form = layui.form;
  
});
layui.use('layer', function(){
  var layer = layui.layer;
  
  
}); 
</script>	
	</div>


<script type="text/javascript">


//================增加数据=============================
$(function(){
    $('.fybtn').click(function(){

//获取当前时间 判断是否在前面加0
function getNow(s) {
return s < 10 ? '0' + s: s;
}
 
var myDate = new Date();            
 
var year=myDate.getFullYear();        //获取当前年
var month=myDate.getMonth()+1;   //获取当前月
var date=myDate.getDate();            //获取当前日
 
 
var h=myDate.getHours();              //获取当前小时数(0-23)
var m=myDate.getMinutes();          //获取当前分钟数(0-59)
var s=myDate.getSeconds();
 
var now=year+'-'+getNow(month)+"-"+getNow(date)+" "+getNow(h)+':'+getNow(m)+":"+getNow(s);

//获取当前时间结束

        var name = $('.name').val();
        var nr = $('.nr').val();
		var data= {
                data: JSON.stringify({
                    'name': name,
                    'nr': nr,
                    'action':1,
                }),
            }


        $.ajax({
            type: 'POST',
            url: '/bbs',
            data: data,  // 这个data是要post的数据
            success: function(data){  // 这个data是接收到的响应的实体
                layer.msg('留言成功');
				$(".bbs_list ul").prepend('<li><div class="bbs_name"><span>'+ name +'</span><i>'+ now +'</i></div><div class="bbs_nr">'+ nr +'</div></li>'); 
				window.location.reload(); // 刷新页面
            }
        });
    });
});
	
//=====================删除数据==========================================

function delete_order(ID){    
	confirm_ = layer.confirm('你确定要删除该条数据吗?',{
			btn: ['确定','取消'] //按钮
			 ,yes:function(index, layero){
	        var id = ID;
			var data= {
	                data: JSON.stringify({
	                    'id': id,
	                    'action':2,
	                }),
	            }
			$.ajax({
			type:"POST",
			url:'/bbs', //它负责将数据,传送到后台服务器去执行。
			data:data, 
			success:function(msg){
				layer.msg('恭喜,删除成功!');
				//alert("恭喜,删除成功!");
				//all delete is success,this can be execute
				$(".li_"+ID).remove(); //删除成功前台移除该行
			} 
			});
			//layer.msg('修改成功', {icon: 1});
			layer.close(index);
			}
		 
		 
		});
	
};


//=================================修改数据======================================
$(document).ready(function(){  
   $(".update").click(function(){ 

        var id=$(this).closest(".bbs_name").find(".num").text();
        var name=$(this).closest(".bbs_name").find("em").text();
        $('.uname').val(name);
        var nr=$(this).closest("li").find(".bbs_nr").text();
        $('.unr').val(nr);

		layer.open({
		type:1,
		//shade:0,
		area:['600px','320px'],
		btnAlign:'c',
		content:$('#renew'),
		closeBtn:0,//右上角箭头样式 0则隐藏
		btn: ['提交数据','关闭窗口']
		,yes:function(index, layero){

		var uname = $('.uname').val();
        var unr = $('.unr').val();

		var data= {
            data: JSON.stringify({
                'id': id,
                'name':uname,
                'nr':unr,
                'action':3,
            }),
        }	

		$.ajax({
		type:"POST",
		url:'/bbs', //它负责将数据,传送到后台服务器去执行。
		data:data, 
		dataType : "html",
		success:function(data){//执行成功之后的回调函数  
		//var data1=$(data).find(".datalist").html();
		//curul.html(data1);
		//var data2=$(data).find("#jscode").html();
		//$("#tiles2").html(data2);
		window.location.reload(); // 刷新页面
		}  
		});
		layer.msg('修改成功', {icon: 1});
		layer.close(index);
		}
		
		,btn2: function(index, layero){

         $("#zhhh1").attr("value","");

                                      }
		
		
		
		}
		
		);

   })	   
  })





    //点击清空输入框
    $('.clearbtn').on('click',function () {
        $('.result').html('');
        $('.txt').html('');
    })
</script>
</body>
</html>

 

欢迎留下你的看法

共 0 条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注