【问题标题】:How can I catch an exception when I use motor to insert data?使用电机插入数据时如何捕获异常?
【发布时间】:2013-11-03 07:28:36
【问题描述】:
#some code

@tornado.gen.engine
def do_insert():
    result = yield motor.Op(db.test_collection.insert, {'_id': 1})

try:
    do_insert()
except:
    print "error"

#some code

我试过这样的代码。数据库是mongodb。 我第一次运行它时,它会正确插入数据。 我第二次运行它,它应该有一个异常并打印“错误”。但它崩溃了,而不是打印“错误”。

【问题讨论】:

    标签: mongodb python-2.7 tornado tornado-motor


    【解决方案1】:

    do_insert 是一个异步函数;这意味着调用它会启动一些任务,但它不会立即完成,而且它可能在它返回时还没有完成。要查看结果(如果返回任何内容)或异常(如果失败),您必须等待它完成。这通常意味着您在调用站点也需要一个“yield”(依此类推)。在顶层,您需要运行 IOLoop:在批处理式应用程序中,您可能需要使用 IOLoop.run_sync;在长时间运行的服务器中,您将使用 IOLoop.start 代替。您的示例将是(注意使用 gen.coroutine 而不是 gen.engine;这与 run_sync 效果更好):

    @tornado.gen.coroutine
    def do_insert():
        result = yield motor.Op(db.test_collection.insert, {'_id': 1})
    
    try:
        IOLoop.instance().run_sync(do_insert())
    except:
        print "error"
    

    【讨论】:

      【解决方案2】:

      我在包装的插入方法中发现了错误,它对我有用:

      @tornado.gen.engine
      def do_insert():
          try:
              result = yield motor.Op(db.test_collection.insert, {'_id': 1})
          except:
              <you should log here>
      

      【讨论】:

        猜你喜欢
        • 2021-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 2021-08-22
        • 2013-03-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多