tornado一起来-动态数据(mongodb)

2017-12-15 10:48:25 查看 1914 回复 0

继上篇模版之后,是不是感觉越来越溜了?这么溜的东西一直在模拟数据,这不科学!下面开始简单的动态数据(主角数据库登场)。

主要内容参考《Introduction to Tornado》中文翻译

走起!
文件照着上篇的《tornado一起来-模版继承》来!
中间加几句!贴上代码

main.py

import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from pymongo import MongoClient

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [(r'/', RecommendedHandler)]
        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 = MongoClient("localhost", 27017)
        self.db = conn["bookstore"]
        tornado.web.Application.__init__(self, handlers, **settings)


class RecommendedHandler(tornado.web.RequestHandler):
    def get(self):
        coll = self.application.db.books
        books = coll.find()
        self.render(
            "index.html",
            page_title="Burt's Books | Recommended Reading",
            header_text="Recommended Reading",
            books=books  
        )

class BookModule(tornado.web.UIModule):
    def render(self, book):
        return self.render_string('modules/book.html', book=book)

if __name__ == '__main__':
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

细心的人才估计已经发现区别了

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [(r'/', RecommendedHandler)]
        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 = MongoClient("localhost", 27017)
        self.db = conn["bookstore"]
        tornado.web.Application.__init__(self, handlers, **settings)

封装了初始化,并且在里面加入了mongo的连接。

class RecommendedHandler(tornado.web.RequestHandler):
    def get(self):
        coll = self.application.db.books
        books = coll.find()
        self.render(
            "index.html",
            page_title="Burt's Books | Recommended Reading",
            header_text="Recommended Reading",
            books=books
        )

Handler里面增加mongo的查询

 coll = self.application.db.books
 books = coll.find()

至于mongo怎么装的,这个去问度娘。

数据是这样的

666666

需要注意的地方是 pymongo 貌似改版了,使用方法与教程的不同。

from pymongo import MongoClient
conn = MongoClient("localhost", 27017)

下面可以完善下增删改查功能,及mysql版的。