【问题标题】:Inserting data into mongodb using python使用python将数据插入mongodb
【发布时间】:2013-07-12 23:03:16
【问题描述】:

我应该在每次插入时重新初始化连接吗?

class TwitterStream:
  def __init__(self, timeout=False):
  while True:
    dump_data()

  def dump_data:
    ##dump my data into mongodb    
    ##should I be doing this every time??:
    client=MongoClient()
    mongo=MongoClient('localhost',27017)
    db=mongo.test
    db.insert('some stuff':'other stuff')
    ##dump data and close connection
    #########################

我是否需要打开连接每次我写一个记录?或者我可以假设我每秒写入数据库 5 次,每次大约 10kb,我可以保持连接打开吗?

如果只有一个连接就足够了,我应该在哪里定义保持连接的变量(clientmongodb)?

【问题讨论】:

    标签: python mongodb connection database


    【解决方案1】:

    打开一个在您的程序期间存在的 MongoClient:

    client = MongoClient()
    
    class TwitterStream:
        def dump_data:
            while True:
                db = client.test
                db.insert({'some stuff': 'other stuff'})
    

    打开单个 MongoClient 意味着您只需为其支付一次启动成本,它的连接池将最大限度地降低打开新连接的成本。

    如果您担心偶尔会出现网络问题,请将您的操作包装在异常块中:

    try:
        db.insert(...)
    except pymongo.errors.ConnectionFailure:
        # Handle error.
        ...
    

    【讨论】:

      【解决方案2】:

      打开连接通常是一项昂贵的操作,因此我建议您尽可能地重用它们。

      在 MongoClient 的情况下,您应该能够保持连接打开并继续重用它。但是,随着连接持续时间更长,最终您将开始遇到连接问题。推荐的解决方案是将 MongoClient 配置为使用自动重新连接,并在重试机制中捕获 AutoReconnect 异常。

      这里是上述方法的一个例子,取自http://python.dzone.com/articles/save-monkey-reliably-writing

      while True:
          time.sleep(1)
          data = {
              'time': datetime.datetime.utcnow(),
              'oxygen': random.random()
          }
      
          # Try for five minutes to recover from a failed primary
          for i in range(60):
              try:
                  mabel_db.breaths.insert(data, safe=True)
                  print 'wrote'
                  break # Exit the retry loop
              except pymongo.errors.AutoReconnect, e:
                  print 'Warning', e
                  time.sleep(5)
      

      【讨论】:

      • 非常感谢您对此的出色回答。你能为我指出一些例子吗?一直站在你的立场上,我不知道如何实施。
      猜你喜欢
      • 1970-01-01
      • 2014-06-29
      • 2021-02-13
      • 1970-01-01
      • 2021-02-01
      • 2020-04-15
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多