python连接mongodb集群方法详解

(编辑:jimmy 日期: 2025/5/11 浏览:2)

简单的测试用例

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time
from pymongo import MongoClient
# 连接单机
# single mongo
# c = MongoClient(host="192.168.89.151", port=27017)
# 连接集群
c = MongoClient('mongodb://192.168.89.151,192.168.89.152,192.168.89.153')

大型项目的使用方式

三个目录:

目录a为config目录,存放项目的配置文件,主要由conf.ini和__init__.py组成"htmlcode">

import configparser
 
#定义环境变量
env = 'dev'
profile = env + '.'
 
#从conf.ini中读取变量
config = configparser.ConfigParser()
config.read(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'conf.ini'))
 
for section in config.sections():
  for key, val in config.items(section):
    if key.startswith(profile):
      CONFIG_DICT['{0}_{1}'.format(section, key.replace(profile, '').upper())] = val
 
#通过conf.ini定义变量
MONGO_HOST = CONFIG_DICT['MONGO_HOST']

更多关于python连接mongodb集群方法详解的文章请查看下面的相关文章

一句话新闻

Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。