How can I use the mongolab add-on to Heroku from python?

浪尽此生 提交于 2019-12-02 00:04:20

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

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)

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.

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'})

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!