← 전체로 돌아가기
스킬 python

Python MongoDB 연결

Python에서 MongoDB에 안전하게 연결하는 방법

pythonmongodbdatabaseconnectionssl

Python에서 MongoDB 연결은 pymongo 라이브러리를 쓰면 돼. 특히 인증(authentication)과 SSL 보안 연결이 중요해.

1. 라이브러리 설치

pip install pymongo certifi

2. MongoDB 클라이언트 연결 함수

SSL과 인증을 포함한 연결 함수야. certifi로 SSL 인증서 경로를 쉽게 찾을 수 있어.

import pymongo, certifi, ssl
from pymongo import MongoClient

ca = certifi.where() # SSL 인증서 경로

def get_client(host, port, username, password, db):
    return MongoClient(
        f'mongodb://{host}:{port}/',
        username=username, password=password,
        authSource=db, ssl=True, ssl_cert_reqs=ssl.CERT_NONE
    )

3. 클라이언트 사용

# 클라이언트 생성 예시
client = get_client("cluster0.eonroyn.mongodb.net", "27017", "urustin", "asdf1234", "horanggotgam")

# DB 선택 및 데이터 조회
db = client.horanggotgam
for doc in db["orderList_options"].find():
    print(doc)

여기서 배울 것

  1. `pymongo`로 Python에서 MongoDB 연결하는 법
  2. SSL을 사용한 보안 연결 설정 방법
  3. 인증 정보를 포함한 `MongoClient` 사용법
  4. `certifi`를 활용해 SSL 인증서 경로 관리하기
원본 파일 보기 (.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