pymongo 连接MongoDB的几种方式
pymongo 连接MongoDB数据库,分为无权限认证和有权限认证两种。
关于如何设置mongodb权限认证,请见米扑博客: MongoDB 用户认证权限总结
添加用户权限认证
1. 添加用户
root@ubuntu:~/script# mongo
MongoDB shell version: 2.6.4
connecting to: test
> use admin // 切换到管理员 admin 数据库
switched to db admin
> show collections
system.indexes
system.users
system.version
> db.system.users.count()
1
> db.addUser('admin','123456') // 在 admin 数据库,添加超级管理员用户 'admin', 密码'123456'
WARNING: The 'addUser' shell helper is DEPRECATED. Please use 'createUser' instead
Successfully added user: { "user" : "admin", "roles" : [ "root" ] }
> db.system.users.find()
{ "_id" : "db_blog.blog_user", "user" : "blog_user", "db" : "db_blog", "credentials" : { "MONGODB-CR" : "1358889f06fc384a21f0e316ff1750ab" }, "roles" : [ { "role" : "dbOwner", "db" : "db_blog" } ] }
{ "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "MONGODB-CR" : "95ec4261124ba5951720b199908d892b" }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
2. 删除用户
> db.removeUser('admin')
WARNING: db.removeUser has been deprecated, please use db.dropUser instead
true
3. 修改用户
修改用户,就是先删除现有用户,再添加同名用户及密码
WARNING: db.removeUser has been deprecated, please use db.dropUser instead
true
> db.addUser('admin', '12345678') // 再添加新用户及密码 'admin' 和 ’12345678'
WARNING: The 'addUser' shell helper is DEPRECATED. Please use 'createUser' instead
Successfully added user: { "user" : "admin", "roles" : [ "root" ] }
方式1: 无用户权限验证
mongo_conn = None try: mongo_conn = pymongo.Connection(host, port) mongo_db = mongo_conn[db_name] mongo_coll = mongo_db[coll_name] print("conn_mongo: %d" % mongo_coll.count()) except Exception as ex: print("conn mongo error: " + str(ex))
方式2: 用户权限验证(1)
连接方式:
mongodb://{username}:{password}@{host}:{port}/{db_name}?authMechanism=MONGODB-CR
代码示例:
uri = "mongodb://{username}:{password}@{host}:{port}/{db_name}?authMechanism=MONGODB-CR".format(username=user_name, password=user_pwd, host=host, port=port, db_name=db_name) print("conn_mongo_2 -- uri: " + uri) mongo_client = pymongo.MongoClient(uri) mongo_db = mongo_client[db_name] mongo_coll = mongo_db[coll_name] print("conn_mongo_2 -- count: %d" % mongo_coll.count())
方式3: 用户权限验证(2)
连接方式:
mongo_client = pymongo.MongoClient("%s:%d"%(host, port))
mongo_client[db_name].authenticate(user_name, user_pwd, db_name, mechanism='MONGODB-CR')
代码示例:
mongo_client = pymongo.MongoClient("%s:%d"%(host, port)) mongo_client[db_name].authenticate(user_name, user_pwd, db_name, mechanism='MONGODB-CR') mongo_db = mongo_client[db_name] mongo_coll = mongo_db[coll_name] print("conn_mongo_3 -- count: %d" % mongo_coll.count())
完整示例:
#!/usr/bin/env python # -*- coding: utf-8 -*- # # PyMongo Authentication Examples # http://api.mongodb.org/python/current/examples/authentication.html import pymongo host = '127.0.0.1' port = 27017 user_name = 'mimvp' user_pwd = '123456' db_name = 'mimvp_blog' coll_name = 'blog_coll' def conn_mongo(): ''' host:port no authenticate ''' mongo_conn = None try: mongo_conn = pymongo.Connection(host, port) mongo_db = mongo_conn[db_name] mongo_coll = mongo_db[coll_name] print("conn_mongo: %d" % mongo_coll.count()) except Exception as ex: print("conn mongo error: " + str(ex)) def conn_mongo_2(): ''' mongodb://username:password@host:port/dbname ''' uri = "mongodb://{username}:{password}@{host}:{port}/{db_name}?authMechanism=MONGODB-CR".format(username=user_name, password=user_pwd, host=host, port=port, db_name=db_name) print("conn_mongo_2 -- uri: " + uri) mongo_client = pymongo.MongoClient(uri) mongo_db = mongo_client[db_name] mongo_coll = mongo_db[coll_name] print("conn_mongo_2 -- count: %d" % mongo_coll.count()) def conn_mongo_3(): ''' host:port client.authenticate(username, password) ''' mongo_client = pymongo.MongoClient("%s:%d"%(host, port)) mongo_client[db_name].authenticate(user_name, user_pwd, db_name, mechanism='MONGODB-CR') mongo_db = mongo_client[db_name] mongo_coll = mongo_db[coll_name] print("conn_mongo_3 -- count: %d" % mongo_coll.count()) if __name__ == '__main__': conn_mongo() conn_mongo_2() conn_mongo_3()
运行结果:
conn_mongo: 33
conn_mongo_2 -- uri: mongodb://youku:123456@127.0.0.1:27017/youku_source_center?authMechanism=MONGODB-CR
conn_mongo_2 -- count: 33
conn_mongo_3 -- count: 33
参考推荐:
PyMongo Authentication Examples(官方)
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2015-05-21 05:05:50
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!