Python连接示例
<p>本文主要介绍Python连接示例。</p>
<p> <img src="https://pcp-portal-sca.obs-cn-shenzhen.pinganyun.com/pcp-portal-sca/20202805102426-10eeabb09ab2.png" style="height:26px; margin:0px; width:65px" />:</p>
<p> • pymongo可单击<a href="https://pypi.org/project/pymongo/" target="_blank">下载</a>。</p>
<p> • 官方资料可参考<a href="https://pymongo.readthedocs.io/en/stable/" target="_blank">PyMongo Documentation</a>。</p>
<p><span style="font-size:18px"><strong>操作步骤</strong></span></p>
<p>1. 执行以下命令,安装pymongo。</p>
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="background-color:#f7f8fa">
<p><span style="font-family:Consolas">pip <strong>install</strong> pymongo</span></p>
</td>
</tr>
</tbody>
</table>
<p>2. 获取 DDS 实例的连接信息。</p>
<p>3. Python安装代码:</p>
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="background-color:#f7f8fa">
<p><span style="font-family:Consolas"><strong>import</strong> uuid</span></p>
<p><span style="font-family:Consolas"><strong>from</strong> pymongo <strong>import</strong> MongoClient</span></p>
<p><span style="font-family:Consolas"> #地址</span></p>
<p><span style="font-family:Consolas">CONN_ADDR1 = 'demotest.mongodb.db.cloud.papub:15923'</span></p>
<p><span style="font-family:Consolas">REPLICAT_SET = 'demotest'</span></p>
<p><span style="font-family:Consolas"> username = 'demouser'</span></p>
<p><span style="font-family:Consolas">password = '123456'</span></p>
<p><span style="font-family:Consolas"> #获取mongoclient</span></p>
<p><span style="font-family:Consolas">client = MongoClient([CONN_ADDR1], replicaSet=REPLICAT_SET)</span></p>
<p><span style="font-family:Consolas"> #授权. 这里的user基于test数据库授权</span></p>
<p><span style="font-family:Consolas">client.admin.authenticate(username, password)</span></p>
<p><span style="font-family:Consolas"> #使用test数据库的collection:testColl做例子, 插入doc, 然后根据DEMO名查找</span></p>
<p><span style="font-family:Consolas">demo_name = 'python-' + str(uuid.uuid1())</span></p>
<p><span style="font-family:Consolas"><strong>print</strong> 'demo_name:', demo_name</span></p>
<p><span style="font-family:Consolas"> doc = dict(DEMO=demo_name, MESG="Hello ApsaraDB For MongoDB")</span></p>
<p><span style="font-family:Consolas">doc_id = client.test.testColl.insert(doc)</span></p>
<p><span style="font-family:Consolas"><strong>print</strong> 'doc_id:', doc_id</span></p>
<p><span style="font-family:Consolas"> <strong>for</strong> d <strong>in</strong> client.test.testColl.find(dict(DEMO=demo_name)):</span></p>
<p><span style="font-family:Consolas"> <strong>print</strong> 'find documents:', d</span></p>
</td>
</tr>
</tbody>
</table>
提交成功!非常感谢您的反馈,我们会继续努力做到更好!