我怎么能从python中使用mongolab附加到Heroku?


1 Answers

我正在使用以下内容:

import os
from urlparse import urlsplit
from pymongo import Connection

url = os.getenv('MONGOLAB_URI', 'mongodb://localhost:27017/testdb')
parsed = urlsplit(url)
db_name = parsed.path[1:]

# Get your DB
db = Connection(url)[db_name]

# Authenticate
if '@' in url:
    user, password = parsed.netloc.split('@')[0].split(':')
    db.authenticate(user, password)
Question

文档只是谈论如何从ruby做到这一点。




我认为这样的事情应该工作:

import os
import sys
import pymongo


mongo_url = os.getenv('MONGOLAB_URI', 'mongodb://localhost:27017')
db_name = 'mongotest'

if __name__ == '__main__':
  try:
   connection = pymongo.Connection(mongo_url)
   if 'localhost' in self.mongo_url:
     db_name = 'my_local_db_name'
   else:
     db_name = self.mongo_url.rsplit('/',1)[1]
   database = connection[db_name]
  except:
   print('Error: Unable to Connect')
   connection = None

if connection is not None:
  database.test.insert({'name': 'foo'})



Related