tornado mongodb查询字典

10 篇文章 0 订阅
8 篇文章 0 订阅

首先需通过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上查询显示。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值