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

前端 未结 5 1327
旧时难觅i
旧时难觅i 2021-01-14 13:43

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

相关标签:
5条回答
  • 2021-01-14 14:26

    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)
    
    0 讨论(0)
  • 2021-01-14 14:28

    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'})
    
    0 讨论(0)
  • 2021-01-14 14:36

    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

    0 讨论(0)
  • 2021-01-14 14:38

    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.

    0 讨论(0)
  • 2021-01-14 14:42

    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()
    
    0 讨论(0)
提交回复
热议问题