首先需通过python在mongodb 中创建字典:
from pymongo import MongoClient
from bson.objectid import ObjectId
from datetime import datetime
client = MongoClient()
print(client.database_names())
db = client['example']#新建数据库
db.example.insert({"word": "oarlock", "definition": "A device attached to a rowboat to hold the oars in place"})
print(client.database_names())
db.example.insert({"word": "perturb", "definition": "Bother, unsettle, modify"})
my_collection = db.example
cursor = my_collection.find()
print(cursor.count()) # 获取文档个数
for item in cursor:
print(item)
运行结果如下图所示:
证明添加的文档数量为2 :有2个id号。
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"/(\w+)", WordHandler)]
#conn = pymongo.Connection("localhost", 27017)
#self.db = conn["example"]
client = MongoClient()
self.db=client['example']#有example数据库则连接,没有则创建
tornado.web.Application.__init__(self, handlers, debug=True)
class WordHandler(tornado.web.RequestHandler):
def get(self, word):
print("11111111")
coll = self.application.db.example
word_doc = coll.find_one({"word": word})
if word_doc:
del word_doc["_id"]
self.write(word_doc)
else:
self.set_status(404)
self.write({"error": "word not found"})
if __name__ == "__main__":
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
浏览器输入网址:http://localhost:8000/oarlock
浏览器输入网址:http://localhost:8000/perturb
主要是将字典保存在mongdb中,而后通过tornado在web上查询显示。