Reputation: 4429
I am running a flask application in python as a means to provide a GUI for manipulating a JSON dictionary and validating it with a JSON schema.
What is the best way to hold the dictionary to be able to change it and save it throughout different requests. My users will be running this locally so there shouldn't be any concurrency problems with multiple users editing it at the same time. I was planning on having a global level variable for the JSON dictionary and having a function run after users make a POST request to change it and just keep it in memory like that until I am done and save it out to a text file. Is this a reasonable method? Or should I not hold it globally and save it to a file each time there are changes and then pull it back up the next time I need to edit it?
Is there another way of doing this that would be more reasonable in flask? I would prefer not to use any sort of database as JSON is just a text format so it is much simpler to just save it to a file after the user is done and then it is ready to use next time.
Upvotes: 0
Views: 260
Reputation: 166
Honestly, a MongoDB instance is so simple to set up, that I think it outweighs the convenience that "just a text file" gives. If I were doing this on my machine I would run it as two docker containers, (app and db) and start it with docker compose. But if you are going to set it up on other peoples machines it might be easier to just install mongo separately, considering different OSes and all.
With mongo running, just write a simple mongo connector (a very simple example I used for a recent project, not the cleanest but it shows the gist):
from pymongo import MongoClient
class DB:
def __init__(self):
self.client = MongoClient('localhost', 27017)
self.db = self.client.email_db
def save_email(self, email):
if not self.email_exists(email):
self.insert(email)
return True
else:
print('email already stored.')
return False
def insert(self, email):
try:
collection = self.db.emails
collection.insert(email.to_dict())
except Exception as e:
print('An error occurred when inserting email: {}'.format(email.hash), e)
def email_exists(self, email):
query = {
'hash': email.hash,
}
try:
collection = self.db.emails
cursor = collection.find(query)
return cursor.count() > 0
except Exception:
print('Could not query db for email: {}'.format(email.hash))
return False
Upvotes: 2
Reputation: 2399
You may find this link helpful. It does what you're asking for, albeit as a database, but there's nothing stopping you from making it a database of strings, where each string is an entire JSON file. The main advantage over a global dictionary is persistence across sessions, which means you wouldn't have to save anything to a text file.
Upvotes: 0