gpt4 book ai didi

python - Motor 和 MongoDB 返回 None

转载 作者:可可西里 更新时间:2023-11-01 09:46:05 24 4
gpt4 key购买 nike

我使用 Motor 驱动程序进行异步访问以读取 mongo 集合。当我运行我的应用程序时,它返回 None 值。当我与 PyMongo 同步运行它时,它运行正常。我在这两个地方都遵循了示例:http://blog.mongodb.org/post/30927719826/motor-asynchronous-driver-for-mongodb-and-pythonhttp://emptysquare.net/motor/pymongo/api/motor/tutorial.html .

这是我的部分代码:

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import tornado.options
from tornado import gen
from bson import json_util
import json
import os.path
import motor

events = []

class WSHandler(tornado.websocket.WebSocketHandler):
@tornado.web.asynchronous
@gen.engine

def open(self):
import traceback
global events
print "tailing for events %s...." % events

try:
coll = db.blah_tail
cursor = coll.find(
{ "$and" : [
{"term": {"$in": events}},
{ "$or" : [
{"coordinates.type" : "Point"},
{"place.full_name" : {"$ne" : None}}
]}
]},
{"coordinates" : 1, "place.full_name" : 1},
tailable = True, timeout = False )

while cursor.alive:

try:
doc = yield motor.Op(cursor.next_object)
print doc
self.write_message(json.dumps(doc, default = json_util.default))
except StopIteration:
pass



db = motor.MotorConnection().open_sync().blah

if __name__ == "__main__":
print 'Server is alive.....'
app = tornado.web.Application(
handlers=[(r'/', MainHandler),
(r'/ws', WSHandler)
], db=db,
template_path=os.path.join(os.path.dirname(__file__), "templates"),
debug=True)

tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()

Motor 使应用程序异步,但我不确定为什么它基本上不从数据库中的集合中读取任何内容。

谢谢

最佳答案

能够通过将代码修改为:

doc = yield motor.Op(cursor.next_object)
if doc:
print doc
self.write_message(json.dumps(doc, default = json_util.default))

因此,如果第一次调用未返回文档,请防止返回 None。 Motor 的创建者的摘录更好地解释为:“问题是,仅仅因为 cursor.alive 是 True 并不能真正保证 next_object 实际上会返回一个文档。如果 find 根本没有匹配任何文档,则第一次调用返回 None .. ”,(http://emptysquare.net/blog/category/motor/)。

关于python - Motor 和 MongoDB 返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13423472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com