子沐课堂——Flask留言板

1.flask安装

pip install flask

2.入口文件配置

代码如下:

#-*- coding:utf-8 -*-  

from flask import Flask,render_template,request,redirect,escape,Markup
from datetime import datetime
#引入Mysql
import MySQLdb
import sys

reload(sys)
sys.setdefaultencoding('utf8')`

#申请空间
app=Flask(__name__)

#127.0.0.1:8000
@app.route('/')
def hello_world():
    list=load_data()
    return render_template('index.html',list=list)    

@app.route('/post',methods=['POST'])
def post():
    name=request.form.get('name',u'匿名').encode('utf-8')
    comment=request.form.get('comment',u'暂无留言').encode('utf-8')
    create_time=datetime.now()
    save_data(name,comment,create_time)
    return redirect('/')

def save_data(name,comment,create_time):
    #连接数据库
    conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root',passwd='root',db='block',charset='utf8')
    cur=conn.cursor()
    cur.execute('set names utf8')
    #插入的sql语句
    sql=u"insert into word (`name`,comment,create_time) values ('{0}','{1}','{2}')".format(name.encode('utf-8'),comment.encode('utf-8'),create_time)
    #执行插入方法
    cur.execute(sql)
    cur.close()
    conn.commit()
    conn.close()

#加载列表    
def load_data():
    # 连接数据库
    conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='block',charset='utf8')
    cur = conn.cursor()
    cur.execute('set names utf8')
    sql='select * from word'
    cur.execute(sql)
    list=cur.fetchall()
    cur.close()
    conn.commit()
    conn.close()
    return list

#使datetime对象更容易分辨的模板的过滤器
@app.template_filter('datetime_fmt')
def datetime_fmt_filter(dt):
    return dt.strftime('%Y年%m月%d日 %H:%M:%S')
#将换行符置换为br标签的模板过滤器
@app.template_filter('nl2br')
def nl2br_filter(s):
    return escape(unicode(s)).replace('\\n',Markup('<br>'))

#执行flask项目
if __name__ == '__main__':
    app.run()

3.搭建页面

使用Bootstrap,搭建HTML页面,新建一个temolates目录,然后再找个目录下新建一个index.html。在模板文件中,我们使用Jinja2模板引擎,判断后台传递来的数据是否为空,非空则显示列表,空则显示暂无数据,同时使用Bootstrap的模态框,制作发布留言。
代码如下:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>留言板</title>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">

    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="/static/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <h1>留言列表<button class="btn btn-warning pull-right" data-toggle="modal" data-target="#blockModal">发布留言</button></h1>
            {% if list %}
            {% for item in list %}
            <div class="panel panel-default">
                    <div class="panel-heading">{{item[1]}} </div>
                    <div class="panel-body">
                        <p class="text-muted">发布时间:{{ item[3]|datetime_fmt}}</p>
                        <p class="text-primary">{{item[2]|nl2br}}</p>
                </div>
            </div>
            {% endfor %}
            {% else %}
            <blockquote>
                    <p class="text-danger">暂无数据</p>
            </blockquote>
            {% endif %}
        </div>
        </div>
    <div class="modal fade" id="blockModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">
                            <span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                        </button>
                        <h4 class="modal-title" id="myModalLabel">发布留言</h4>
                    </div>
                    <form class="form-horizontal" role="form" action="/post" method="post">
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="name" class="col-sm-2 control-label">姓名</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="name" placeholder="请输入你的名字" name="name">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="comment" class="col-sm-2 control-label">留言内容</label>
                            <div class="col-sm-10">
                                <textarea class="form-control" rows="3" name="comment" id="comment"></textarea>
                            </div>
                        </div>
                   </div>
                   <div class="modal-footer">
                       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                       <button type="submit" class="btn btn-primary">发布</button>
                   </div>
               </form>
           </div>
       </div>
   </div>
</body>
</html>

随后我们新建static文件夹,里面方式我们从Bootstrap官网下载的文件资源包

4.运行

cmd输入命令,python index.py
如此,就可以通过浏览器访问127.0.0.1:5000,显示的项目

5.自定义端口及开启调试模式

修改index.py,设置app.run()app.run('127.0.0.1',8080,debug=True),如此每次代码改变,不需要手动重新启动项目。flask会自动重启项目。
今日头条——原文链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

子沐老司

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

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

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

打赏作者

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

抵扣说明:

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

余额充值