3

The documentation only talks about how to do it from ruby.

Jameson Quinn
  • 1,060
  • 15
  • 21

5 Answers5

11

This is Will from MongoLab. We have a generic example of how to connect in Python using the official python driver (pymongo). This example is not for connecting from Heroku per say but it should be similar. The difference is that you will need to pluck your driver config from your Heroku ENV environment to supply to the driver.

https://github.com/mongolab/mongodb-driver-examples/blob/master/python/pymongo_simple_example.py

If you still have trouble feel free to contact us directly at support@mongolab.com

-will

will
  • 667
  • 4
  • 6
7

I'm using the following:

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)
kynan
  • 13,235
  • 6
  • 79
  • 81
4

Get the connection string settings by running heroku config on the command line after installed the add-on to your heroku app.

There will be an entry with the key MONGOLAB_URI in this form:

MONGOLAB_URI => mongodb://user:pass@xxx.mongolab.com:27707/db

Simply the info from the uri in python by creating a connection from the uri string.

Tyler Brock
  • 29,626
  • 15
  • 79
  • 79
2

I think something like this should work:

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'})
kelsmj
  • 1,183
  • 11
  • 18
2

PyMongo now provides a get_default_database() method that makes this entire exercise trivial:

from pymongo import MongoClient

client = MongoClient(os.environ['MONGOLAB_URI'])
db = client.get_default_database()
Dan Gayle
  • 2,277
  • 1
  • 24
  • 38