import pymongo
connection = None
db = None
def save_to_database(database_name, products):
global connection
__connect(database_name)
for product in products:
__save(product)
__close_connection()
def __save(product): db['sainsburys'].insert_one(product.__dict__)
def __connect(database):
global connection, db
connection = pymongo.MongoClient()
db = connection[database]
def __close_connection():
if connection:
connection.close()
Saving the “basic” dictionary to the MongoDB database works straight out of the box. Because the database stores objects as they are, you don’t have to do any conversions. And you can reuse the code for saving to a JSON file. Yes, even for classes.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.