Skip to content

Instantly share code, notes, and snippets.

@aasmpro
Created March 24, 2022 21:56
Show Gist options
  • Save aasmpro/98e7f8314fcd4d33fe51651e1e5a8568 to your computer and use it in GitHub Desktop.
Save aasmpro/98e7f8314fcd4d33fe51651e1e5a8568 to your computer and use it in GitHub Desktop.
Simple todo app with saving data in json file
import json
import sys
class DataList:
notes = []
@staticmethod
def print(notes):
"""
print notes
"""
for note in notes:
note.print()
print("-----------------------------------------")
@staticmethod
def serialize():
data = []
for note in DataList.notes:
data.append(note.serialize())
return data
@staticmethod
def deserialize(notes):
data = []
for note in notes:
data.append(Note(**note))
return data
@staticmethod
def write():
"""
write data to data.json file (like a database)
"""
data = DataList.serialize()
with open("data.json", "w+") as file:
file.write(json.dumps(data))
@staticmethod
def read():
"""
read data from data.json file (like a database)
"""
with open("data.json", "r+") as file:
try:
DataList.notes = DataList.deserialize(json.loads(file.read()))
except json.decoder.JSONDecodeError as e:
pass
@staticmethod
def search():
"""
search a title in notes titles and print a list
"""
note_title = input("Note Title: ")
data = []
for note in DataList.notes:
if note.title_contains(note_title):
data.append(note)
DataList.print(data)
class Note:
def __init__(self, title, description):
self.title = title
self.description = description
def print(self):
print("Title: {}".format(self.title))
for line in self.description:
print(line)
def serialize(self):
return {"title": self.title, "description": self.description}
def title_contains(self, str):
return self.title.find(str) >= 0
@staticmethod
def create(notes):
"""
create new note and add it to the list of notes
"""
title = input("Title: ")
prev_line = ""
description = []
while True:
if not description:
desc = input("Description: ")
else:
desc = input(" ")
if desc == "" and prev_line == "":
break
prev_line = desc
description.append(desc)
# fixme: better to handle it with conditions...
note = Note(title, description[:-1])
notes.append(note)
print("Note created successfully.")
def print_help():
print("you should provide an option.")
print(" -l print notes list")
print(" -c create new note")
print(" -s search in note titles")
def main():
# get the command from user
try:
command = sys.argv[1]
except Exception as e:
print_help()
return
# load data from data.json
DataList.read()
if command == "-l":
"""
print notes list
"""
DataList.print(DataList.notes)
elif command == "-c":
"""
add new item
"""
Note.create(DataList.notes)
DataList.write()
elif command == "-s":
"""
search notes to get one containing the title
"""
DataList.search()
else:
print_help()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment