Last active
June 24, 2019 09:39
-
-
Save enricorotundo/f2b122743fd46cc86a06eabcd97e4b5f to your computer and use it in GitHub Desktop.
Pymongo connection with a pinch of flavour
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import urllib | |
from pymongo import MongoClient | |
def get_conn_string() -> str: | |
conn_string = "mongodb://{}:{}@{}/{}".format( | |
os.getenv("DB_USER"), | |
urllib.parse.quote(os.getenv("DB_PWD")), # escapes invalid chars | |
os.getenv("DB_URI"), | |
os.getenv("DB_NAME"), | |
) | |
return conn_string | |
def get_client() -> MongoClient: | |
client = MongoClient(get_conn_string()) | |
return client | |
# usage | |
client = get_client() | |
db = client.get_database() | |
# from here on see http://api.mongodb.com/python/current/api/pymongo/database.html#pymongo.database.Database | |
# Example: push pandas dataframe | |
# client.get_database().COLLECTION_NAME.insert_many(df.to_dict(orient="records")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment