How to escape @ in a password in pymongo connection?

后端 未结 3 857
旧时难觅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 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")
    

提交回复
热议问题