《Introduction to Tornado》笔记06 — 基于tornado与mongodb实现一个简单的图书增删改查

说明

这是一个基于tornado+mongodb的纯练手的项目,使用前端模板实现数据的展示与提交。

项目的目录结构如下

app.py是项目的启动文件。

mongodb_operator.py用来想mongodb数据库中插入数据。 

效果如下(没有写css,看效果就好了)

往数据库中写入数据

# -*- coding:utf-8 -*-
import pymongo

client = pymongo.MongoClient("localhost", 27017)
# 数据库 —— bookManagement
db = client["bookManagement"]
# 集合 —— data
collection = db.data
# 插入数据
book1 = {"title":"Naruto","author":"whw1"}
book2 = {"title":"Sasuke","author":"whw2"}
book3 = {"title":"Sakurua","author":"whw3"}
book4 = {"title":"Maitogai","author":"whw4"}
collection.insert_many([book1,book2,book3,book4])

app.py中的内容 —— tornado增删改查的主逻辑

# -*- coding:utf-8 -*-
import os.path
import tornado.locale
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
import pymongo


define("port", default=8005, help="run on the given port", type=int)

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            # 主页
            (r"/", MainHandler),
            # 书籍列表页
            (r"/recommended", RecommendedHandler),
            # 书籍详情编辑页
            (r"/edit/(\w+)", BookEditHandler),
            # 添加书籍
            (r"/add", BookAddHandler),
            # 删除书籍 —— 要求title一致~~
            (r"/del/(\w+)", BookDelHandler),
        ]
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__),"templates"),
            static_path=os.path.join(os.path.dirname(__file__),"static"),
            ui_modules={"Book": BookModule},
            debug=True,
        )
        conn = pymongo.MongoClient("localhost", 27017)
        # 连 bookManagement 库
        self.db = conn["bookManagement"]
# 执行父类__init__方法 tornado.web.Application.
__init__(self, handlers,**settings)
class MainHandler(tornado.web.RequestHandler): def get(self): self.render( "index.html", page_title = "Burt's Books | Home", header_text = "火之国图书管理系统", ) class RecommendedHandler(tornado.web.RequestHandler): def get(self): # 集合 coll = self.application.db.data # 使用find方法获取书籍文档的列表! books = coll.find() self.render( "recommended.html", page_title = "Burt's Books | Recommended Reading", header_text = "熟悉的增删改查", books = books ) class BookEditHandler(tornado.web.RequestHandler): def get(self,title=None): book = dict() if title: # 选择集合 coll = self.application.db.data # 根据传过来的title,获取书籍对象 —— 需要title唯一~~~ book = coll.find_one({"title":title}) self.render( "book_edit.html", page_title = "编辑书籍", header_text = "编辑书籍页面", book=book ) def post(self,title=None): book_fields = ["title","author"] # 选择集合 coll = self.application.db.data book = {} if title: book = coll.find_one({"title":title}) for key in book_fields: # self.get_argument获取前端form表单post请求发来的数据 book[key] = self.get_argument(key,None) if title: # 保存 coll.save(book) else: # 如果书名不存在的话,将这本书插入到数据库中华 coll.insert(book) # 重定向 self.redirect("/recommended") class BookAddHandler(tornado.web.RequestHandler): def get(self): self.render( "book_add.html", page_title="添加书籍", header_text="添加书籍页面", ) def post(self): book_fields = ["title", "author"] # 选择集合 coll = self.application.db.data book = {} for key in book_fields: # self.get_argument获取前端form表单post请求发来的数据 book[key] = self.get_argument(key, None) # 保存 coll.save(book) # 重定向 return self.redirect("/recommended") class BookDelHandler(tornado.web.RequestHandler): def get(self,title=None): if title: # 选择集合 coll = self.application.db.data # 根据传过来的title,删除书籍对象 —— 需要title唯一~~~ coll.remove({"title": title}) # 重定向 return self.redirect("/recommended") class BookModule(tornado.web.UIModule): def render(self, book): return self.render_string( "modules/book.html", book=book, ) def css_files(self): return "/static/css/recommended.css" def javascript_files(self): return "/static/js/recommended.js" if __name__ == "__main__": tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()

模板文件中的内容

index页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{page_title}}</title>
</head>
<body>
<h1 style="color: red;">{{header_text}}</h1>
<h2><a href="/recommended">前往增删改查页面</a></h2>

</body>
</html>

recommended页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{page_title}}</title>
</head>
<body>
<h1 style="color: cornflowerblue">{{header_text}}</h1>
<h2><a href="/">前往主页面</a></h2>
{# 先展示出所有的书籍与作者,每个书籍的title新加连接,跳转到书籍详情的编辑页面 #}
{# post请求 #}
<form action="" method="post">
    {% for book in books %}
    <a href="/edit/{{ book.get("title") }}">{{book.get("title")}}</a>
    <span>{{book.get("author")}}(点击书名编辑)</span> <a href="/del/{{ book.get("title") }}" type="button">删除</a>
    <br><br>
    {% end %}
    {# 添加书籍 #}
    <a href="/add" >添加书籍</a>
</form>

</body>
</html>

book_edit页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{page_title}}</title>
</head>
<body>
<h1 style="color: red">{{ header_text }}</h1>
<hr>
<hr>
    <form action="" method="post">
        {# name最好跟数据库中的字段名一致!!! #}
        title:<input type="text" value="{{ book.get("title") }}" name="title">
        <br><br>
        author:<input type="text" value="{{ book.get("author") }}" name="author" >
        <br><br>
        <input type="submit">
    </form>
</body>
</html>

book_add页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{page_title}}</title>
</head>
<body>
<h1 style="color: red">{{ header_text }}</h1>
<form action="" method="post">
    {# name的值最好跟数据库的字段一致!! #}
    书名:<input type="text" name="title">
    <br>
    作者:<input type="text" name="author">
    <br>
    <input type="submit">
</form>
</body>
</html>

~~~

posted on 2019-11-27 11:51  江湖乄夜雨  阅读(180)  评论(0编辑  收藏  举报