How to escape @ in a password in pymongo connection?

后端 未结 3 851
旧时难觅i
旧时难觅i 2020-12-15 18:13

My question is a specification of how can i validate username password for mongodb authentication through pymongo?.

I\'m trying to connect to a MongoDB instance using

相关标签:
3条回答
  • 2020-12-15 18:57

    run in terminal :

    python -m pip install pymongo[srv]
    

    python file:

    import pymongo
    from pymongo import MongoClient
    import urllib.parse
    
    username = urllib.parse.quote_plus('username')
    password = urllib.parse.quote_plus("password")
    
    url = "mongodb+srv://{}:{}@cluster0-0000.mongodb.net/<dbname>?retryWrites=true&w=majority".format(username, password)
    # url is just an example (your url will be different)
    
    cluster = MongoClient(url)
    db = cluster['Sample']
    collection = db['temporary']
    
    0 讨论(0)
  • 2020-12-15 19:09

    You should be able to escape the password using urllib.quote(). Although you should only quote/escape the password, and exclude the username: ; otherwise the : will also be escaped into %3A.

    For example:

    import pymongo 
    import urllib 
    
    mongo_uri = "mongodb://username:" + urllib.quote("p@ssword") + "@127.0.0.1:27001/"
    client = pymongo.MongoClient(mongo_uri)
    

    The above snippet was tested for MongoDB v3.2.x, Python v2.7, and PyMongo v3.2.2.

    The example above assumed in the MongoDB URI connection string:

    • The user is created in the admin database.
    • The host mongod running on is 127.0.0.1 (localhost)
    • The port mongod assigned to is 27001

    For Python 3.x, you can utilise urllib.parse.quote() to replace special characters in your password using the %xx escape. For example:

    url.parse.quote("p@ssword")
    
    0 讨论(0)
  • 2020-12-15 19:15

    Python 3.6.5 - PyMongo 3.7.0 version for connecting to an mlab instance:

    from pymongo import MongoClient
    import urllib.parse
    
    username = urllib.parse.quote_plus('username')
    password = urllib.parse.quote_plus('password')
    client = MongoClient('mongodb://%s:%s@ds00000.mlab.com:000000/recipe_app_testing' % (username, password))
    

    This is the only way I have managed to connect to the mlab MongoDB instance without using flask-pymongo spun up app, I needed to create fixtures for unit tests.

    Python 3.6.5 - PyMongo 3.7.0 localhost version:

    from pymongo import MongoClient
    import urllib.parse 
    
    username = urllib.parse.quote_plus('username')
    password = urllib.parse.quote_plus('password')
    client = MongoClient('mongodb://%s:%s@127.0.0.1:27001/' % (username, password))
    
    0 讨论(0)
提交回复
热议问题