我有一个 python 脚本正在运行以将文档添加到远程 mongodb 数据库的集合中。该文件如下:
from pymongo import Connection
ip = 'x.x.x.x' #edited out
conn = Connection()
db = conn['netmon']
users = db.users
print 'number of users: ' + str(users.count())
if users.count() == 0:
print 'Please create a new account.'
t_user = raw_input('Username:')
users.insert({'username':unicode(t_user)})
conn.close()
当我运行这个脚本时,我有一些有趣的行为。在服务器日志中,似乎接受了连接,运行了查询,然后关闭了连接。
# Mongodb logs
14:27:18 [initandlisten] connection accepted from 108.93.46.75:39558 #1
14:27:18 [conn1] run command admin.$cmd { ismaster: 1 }
14:27:18 [conn1] command admin.$cmd command: { ismaster: 1 } ntoreturn:1 reslen:71 0ms
14:27:18 [conn1] run command netmon.$cmd { count: "users", fields: null, query: {} }
14:27:18 [conn1] Accessing: netmon for the first time
14:27:18 [conn1] command netmon.$cmd command: { count: "users", fields: null, query: {} } ntoreturn:1 reslen:58 10ms
14:27:18 [conn1] end connection 108.93.46.75:39558
但是,这是我从 python 脚本中得到的:
# Python error
> python testmongo.py
Traceback (most recent call last):
File "testmongo.py", line 7, in <module>
conn = Connection()
File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 290, in __init__
self.__find_node()
File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 586, in __find_node
raise AutoReconnect(', '.join(errors))
pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused
charles@charles-mbp:~/Desktop$ python testmongo.py
Traceback (most recent call last):
File "testmongo.py", line 7, in <module>
conn = Connection()
File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 290, in __init__
self.__find_node()
File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 586, in __find_node
raise AutoReconnect(', '.join(errors))
pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused
charles@charles-mbp:~/Desktop$ python testmongo.py
Traceback (most recent call last):
File "testmongo.py", line 7, in <module>
conn = Connection()
File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 290, in __init__
self.__find_node()
File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 586, in __find_node
raise AutoReconnect(', '.join(errors))
pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused
一些有用的信息: 远程服务器是在 OpenVZ 上运行的 VPS。我知道存在与 count() 和迭代器相关的兼容性问题,但我(假设)通过使用 --smallfiles 选项修复了它们,并将我的 nssize 限制为 100。我两边的防火墙都是完全打开的。
我还注意到,在错误中,自动重新连接正在尝试连接到 localhost,即使我指定了不同的 IP 地址。