Skip to content

Instantly share code, notes, and snippets.

@Farhaduneci
Created March 30, 2024 05:18
Show Gist options
  • Save Farhaduneci/7979c53205142ce83d557c14e481695c to your computer and use it in GitHub Desktop.
Save Farhaduneci/7979c53205142ce83d557c14e481695c to your computer and use it in GitHub Desktop.
Command-Line DB App with Python
"""
This command-line diary application allows users to add, view, search,
and delete diary entries. Entries are stored with timestamps in an
SQLite database.
Original Author: Charles Leifer
Source: https://charlesleifer.com/blog/dear-diary-an-encrypted-command-line-diary-with-python/
"""
import datetime
import sys
from collections import OrderedDict
from peewee import DateTimeField, Model, SqliteDatabase, TextField
db = SqliteDatabase(database=None) # Defered Initialization
class Entry(Model):
content = TextField()
timestamp = DateTimeField(default=datetime.datetime.now)
class Meta:
database = db
def menu_loop():
while True:
for key, value in menu.items():
print(f"{key}) {value.__doc__}")
choice = input("Action: ").lower().strip()
if choice in menu:
menu[choice]()
print()
def add_entry():
"""Add entry"""
print("Enter your entry. Press ctrl+d when finished.")
data = sys.stdin.read().strip()
if data and input("Save entry? [Yn] ") != "n":
Entry.create(content=data)
print("Saved successfully.")
def view_entries(search_query=None):
"""View previous entries"""
query = Entry.select().order_by(Entry.timestamp.desc())
if search_query:
query = query.where(Entry.content.contains(search_query))
for entry in query:
timestamp = entry.timestamp.strftime("%A %B %d, %Y %I:%M%p")
print()
print(timestamp)
print("=" * len(timestamp))
print(entry.content, end="\n\n")
print("n) next entry")
print("d) delete entry")
print("q) return to main menu")
action = input("Choice? (Ndq) ").lower().strip()
if action == "q":
break
elif action == "d":
entry.delete_instance()
break
def search_entries():
"""Search entries"""
view_entries(input("Search query: "))
def quit_program():
"""Quit program"""
quit()
menu = OrderedDict(
[
("a", add_entry),
("v", view_entries),
("s", search_entries),
("q", quit_program),
]
)
if __name__ == "__main__":
db.init("diaries.db")
db.create_tables([Entry])
menu_loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment