Python MongoDB 연결
Python에서 MongoDB SSL 연결 기본 코드와 설정.
Python MongoDB 연결
import pymongo
import certifi
from pymongo import MongoClient
import ssl
# certifi는 SSL 인증서 경로 잡음. 없으면 에러남.
ca = certifi.where()
# MongoClient로 연결
# host, port, user, pw, authSource(DB명) 받음
# ssl=True, ssl_cert_reqs=ssl.CERT_NONE 중요
def get_client(host, port, username, password, db):
return MongoClient('mongodb://{}:{}/'.format(host, port),
username=username,
password=password,
authSource=db,
ssl=True, ssl_cert_reqs=ssl.CERT_NONE)
# 연결 예시
# client = get_client("[호스트]", "[포트]", "[유저명]", "[비밀번호]", "[DB명]")
client = get_client("cluster0.eonroyn.mongodb.net", "27017", "urustin", "asdf1234", "horanggotgam")
# DB 선택, 데이터 조회
db = client.horanggotgam
print(db["orderList_options"].find())
certifi로 SSL 인증서 경로 잡음.
ssl_cert_reqs=ssl.CERT_NONE 하면 인증서 검증 건너뜀.
여기서 배울 것
- `pymongo`로 Python에서 MongoDB 연결함.
- `certifi` 사용해서 SSL 인증서 경로 처리.
- `ssl_cert_reqs=ssl.CERT_NONE`로 인증서 검증 건너뜀.
- `MongoClient` 함수에 필요한 파라미터 확인.
원본 파일 보기 (.claude/skills/tn-mongodb-python-connection/SKILL.md)
---
name: Python MongoDB 연결
description: Use this skill when the user asks to connect to MongoDB from a Python application, especially for secure connections with authentication and SSL.
version: 1.0.0
source: /home/son/prj/resume/backup_notes_260317/notion/Tech Note/mongoDb_python 98effb2c830f49d5a81eee2747a5373c.md
---
# mongoDb_python
basic code
```python
import pymongo
import sys
import certifi
ca = certifi.where()
from pymongo import MongoClient
import ssl
# client = pymongo.MongoClient("mongodb+srv://urustin:asdf1234@cluster0.eonroyn.mongodb.net/?retryWrites=true&w=majority", ssl_cert_reqs=ssl.CERT_NONE)
def get_client(host,port,username,password,db):
return MongoClient('mongodb://{}:{}/'.format(host,port),
username=username,
password=password,
authSource=db,
ssl=True,ssl_cert_reqs=ssl.CERT_NONE)
# client = get_client("host-ip","port","username","password","db-name")
client = get_client("cluster0.eonroyn.mongodb.net","27017","urustin","asdf1234","horanggotgam")
db= client.horanggotgam
print(db["orderList_options"].find())
```
both is fine