Python에서 pymongo를 사용하는 예제에 대하여 알아봅니다. pymongo는 파이썬에서 MongoDB를 사용할 수 있는 모듈 이름입니다. 참고로 아래 예제는 Flask를 사용하였습니다.
* 디렉토리 구조
--- app.py
|
|--- templates
|
|--- fruits.html
위 구조와 같이 render_template()은 templates 경로에 위치한 해당 파일을 불러옵니다.
먼저 PyMongo가 설치되지 않은 경우 설치가 필요합니다. pip를 사용하여 pymongo를 설치합니다. 그 전에 pip 패키지 라이브러리를 최신버전으로 업그레이드 하면 좋을 것입니다. 아래와 같이 실행합니다.
$ pip install --upgrade pip
$ pip install pymongo
# app.py
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client.dbName
collection = db.collectionName
results = collection.find()
app.render_template('fruits.html', fruits=results)
client.close()
# fruits.html
아래예제는 첫번째 과일의 name 프로퍼티값을 출력합니다.
PyMongo의 데이터를 불러와 이를 템플릿 fruits.html에 넘겨주어 사용한 예제입니다.