OpenShift Python mongoDB环境变量未设置/无法连接

时间:2014-03-08 20:35:47

标签: python mongodb openshift

这是我的申请文件头:

import os
import sys
from cgi import parse_qs, escape
import pymongo
from pymongo import MongoClient

我安装了mongoDB 2.4档,我正在尝试通过

进行连接
client = MongoClient('mongodb:$OPENSHIFT_MONGODB_DB_HOST:$OPENSHIFT_MONGODB_DB_PORT/')

我收到了错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/var/lib/openshift/531b77fd500446980900010d/python/virtenv/lib/python2.7/site-packages/pymongo/mongo_client.py", line 239, in __init__
    res = uri_parser.parse_uri(entity, port)
  File "/var/lib/openshift/531b77fd500446980900010d/python/virtenv/lib/python2.7/site-packages/pymongo/uri_parser.py", line 269, in parse_uri
    nodes = split_hosts(hosts, default_port=default_port)
  File "/var/lib/openshift/531b77fd500446980900010d/python/virtenv/lib/python2.7/site-packages/pymongo/uri_parser.py", line 209, in split_hosts
    nodes.append(parse_host(entity, port))
  File "/var/lib/openshift/531b77fd500446980900010d/python/virtenv/lib/python2.7/site-packages/pymongo/uri_parser.py", line 137, in parse_host
    raise ConfigurationError("Port number must be an integer.")
pymongo.errors.ConfigurationError: Port number must be an integer.

看起来OPENSHIFT_MONGODB_DB_PORT未设置

print  OPENSHIFT_MONGODB_DB_PORT --> NameError: name 'OPENSHIFT_MONGODB_DB_PORT' is not defined

OPENSHIFT_MONGODB_DB_HOST

相同

建立连接需要做什么?

更新

我能够通过来自rockmongo

的硬编码信息直接通过客户端进行连接
client = MongoClient('mongodb://admin:password@[ip addr]:[port]/') 

但是当我做的时候

client = MongoClient('mongodb:admin:password@%s:%s/' %  os.environ['OPENSHIFT_MONGODB_DB_HOST'], os.environ['OPENSHIFT_MONGODB_DB_PORT'])) 

我得到了

[error] (<type 'exceptions.KeyError'>, KeyError('OPENSHIFT_MONGODB_DB_HOST',), <traceback object at 0x7f7bc8367248>)

1 个答案:

答案 0 :(得分:4)

OpenShift连接变量被定义为环境变量,它们不能作为普通的Python变量访问。因此,您提供的打印声明不起作用,以下应该;

import os
print os.environ['OPENSHIFT_MONGODB_DB_PORT']

您应该将代码更改为;

client = MongoClient('mongodb:%s:%s/' % (os.environ['OPENSHIFT_MONGODB_DB_HOST'], os.environ['OPENSHIFT_MONGODB_DB_PORT))

您可以参考示例here