史高治

新随笔 联系 管理
tornado之日记本——
 
1、diary.py:
 
import time
from model.database import DataBase
from tornado import web, httpserver, ioloop
 
def getDiaryInfo(self):
    t = self.get_argument('time',time.strftime('%Y-%m-%d %X', time.localtime()))
    weather = self.get_argument('weather')
    mood = self.get_argument('mood')
    content = self.get_argument('content')
    return dict(time=t, weather=weather, mood=mood, content=content)
 
class IndexHandler(web.RequestHandler):
    def get(self, *args, **kwargs):
        search=self.get_argument('search','')   #初始搜索词为空,列出所有日记
        diaries=DataBase().getDiaries(search)
        self.render('index之日记本.html',diaries=diaries)
 
class CreateDiaryHandler(web.RequestHandler):
    def get(self, *args, **kwargs):
        self.render('createDiary.html')
    def post(self, *args, **kwargs):
        item=getDiaryInfo(self)
        DataBase().createDiary(item)
        self.redirect('/')
 
class UpdateDiaryHandler(web.RequestHandler):
    def get(self, *args, **kwargs):
        diary=DataBase().getDiaryByID(self.get_argument('id'))
        self.render('updateDiary.html',diary=diary)
    def post(self, *args, **kwargs):
        item=getDiaryInfo(self) #id是get的参数,其他来自post请求
        item.update({'id':self.get_argument('id')})
        DataBase().updateDiary(item)
        self.redirect('/')
 
class DeleteDiaryHandler(web.RequestHandler):
    def get(self, *args, **kwargs):
        id=self.get_argument('id')
        self.write(f'''<form method="post">
        <input type="submit" value="确认删除日记{id}" name="deleteDiary">
        <input type="submit" value="取消删除{id}" name="deleteDiary"></form>''')
    def post(self, *args, **kwargs):
        if '确认' in self.get_argument('deleteDiary'):
            DataBase().deleteDiary(self.get_argument('id'))
        self.redirect('/')
 
class InfoDiaryHandler(web.RequestHandler):
    def get(self, *args, **kwargs):
        diary=DataBase().getDiaryByID(self.get_argument('id'))
        self.render('infoDiary.html',diary=diary)
 
app = web.Application([
    (r'/', IndexHandler),
    (r'/createDiary', CreateDiaryHandler),
    (r'/updateDiary', UpdateDiaryHandler),
    (r'/deleteDiary', DeleteDiaryHandler),
    (r'/infoDiary', InfoDiaryHandler),
],**{'template_path':'templates','static_path':'static'})
 
if __name__ == '__main__':
    httpServer = httpserver.HTTPServer(app)
    httpServer.listen(8080)
    print('http://127.0.0.1:8080')
    ioloop.IOLoop.current().start()
***************分割线***************
2、model文件夹中的database.py:
 
import pymysql
 
class DataBase:
    def __init__(self):
        self.conn=pymysql.connect(host='localhost',port=3306,user='chengy',password='',
            db='tornado之日记本',charset='utf8mb4')
        self.cur=self.conn.cursor(pymysql.cursors.DictCursor)
 
    def operateDatabase(self,sql,insertValues=None):
        self.cur.execute(sql,insertValues)
        self.conn.commit()
        self.cur.close()
        self.conn.close()
 
    def createDiary(self,item):
        sql='insert into diaries(time,weather,mood,content) values(%s,%s,%s,%s)'
        insertValues=(item['time'],item['weather'],item['mood'],item['content'])
        self.operateDatabase(sql,insertValues)
 
    def updateDiary(self,item):
        sql=f'''update diaries set time="{item['time']}",weather="{item['weather']}",
          mood="{item['mood']}",content="{item['content']}" where id={item['id']}'''
        self.operateDatabase(sql)
 
    def deleteDiary(self,id=''):
        sql=f'delete from diaries where id={id}'
        self.operateDatabase(sql)
 
    def getDiaries(self,search=''):
        sql=f'select * from diaries where content like "%{search}%" \
        or weather like "%{search}%" or mood like "%{search}%" limit 25'
        self.operateDatabase(sql)
        return self.cur.fetchall()
 
    def getDiaryByID(self,id=''):
        sql=f'select * from diaries where id={id}'
        self.operateDatabase(sql)
        return self.cur.fetchone()
***************分割线***************
3、templates文件夹
 
index之日记本.html:
 
<h2>日行一事</h2>
<div><a href="/createDiary">新建日记</a><br></div>
<form action="" method="get">
    搜索日记:<input type="text" name="search">
    <input type="submit" value="搜索">
</form>
<br><br>
{% if diaries %}
    <table cellspacing="0" cellpadding="0" border="9">
        <tr><th>修改</th><th>删除</th><th>id</th><th>时间</th>
            <th>天气</th><th>心情</th><th>内容</th></tr>
        {% for diary in diaries %}
            <tr><td><a href="/updateDiary?id={{diary['id']}}">修改</a></td>
            <td><a href="/deleteDiary?id={{diary['id']}}">删除</a></td>
            <td>{{diary['id']}}</td><td>{{diary['time']}}</td><td>{{diary['weather']}}</td>
            <td>{{diary['mood']}}</td>
            <td><a href="/infoDiary?id={{diary['id']}}">{{diary['content'][:20]}}</a></td>
            </tr>   <!--显示前9个字符,tornado用[:9],django用|truncatechars:'9'-->
        {% end %}
    </table>
{% end %}
*****分割线*****
createDiary.html:
 
<h2>新建日记</h2>
<form action="" method="post">
    天气:<input type="text" name="weather"><br>
    心情:<input type="text" name="mood"><br>
    内容:<textarea rows="10" cols="30" name="content"></textarea><br>
    <input type="submit" value="保存">
</form>
*****分割线*****
updateDiary.html:
 
<h2>更新日记</h2>
{% if diary %}
<form action="" method="post">
    时间:<input type="text" name="time" value="{{diary['time']}}"><br>
    天气:<input type="text" name="weather" value="{{diary['weather']}}"><br>
    心情:<input type="text" name="mood" value="{{diary['mood']}}"><br>
    内容:<textarea rows="10" cols="30" name="content">{{diary['content']}}</textarea><br>
    <input type="submit" value="更新">    <!--textarea无value属性,直接写在标签之间-->
</form>
{% end %}
*****分割线*****
infoDiary.html:
 
<h2 style="color: red;">日记详情</h2>
<h3><a href="/">返回首页</a><br><br></h3>
{% if diary %}
    标识:{{diary['id']}}<br>
    时间:{{diary['time']}}<br>
    天气:{{diary['weather']}}<br>
    心情:{{diary['mood']}}<br><br>
    <!--把字符当html解析:对它用raw语法,或在head中加句{% autoescape None %}-->
    {%raw diary['content'].replace('\r\n','<br>').replace(' ',' ')%}
{% end %}   <!--使用时,各篇html代码替换回半角的&及左尖角符-->
posted on 2018-01-03 20:32  史高治  阅读(174)  评论(0编辑  收藏  举报