[diary.py]
#!/user/bin/env python3
import datetime
import sys
import os
from collections import OrderedDict
from peewee import *
db = SqliteDatabase('diary.db')
class Entry(Model):
content = TextField()
timestamp = DateTimeField(default=datetime.datetime.now)
class Meta:
database = db
def initialize():
"""Create database."""
db.connect()
db.create_tables([Entry], safe=True)
def menu_loop():
"""Main menu options"""
choice = None
while choice != 'q':
clear()
print("Press 'q' to quit.")
for key, value in menu.items():
print("{}) {}".format(key, value.__doc__))
choice = input("Action: ").lower().strip()
if choice in menu:
clear()
menu[choice]()
def add_entry():
"""Adds entry."""
print("Write your entry. Press ctrl+D when finished.")
data = sys.stdin.read().strip()
if data:
if input("Save entry? [y/n]: ").lower() != 'n':
Entry.create(content=data)
print("Saved successfully!")
def view_entries(search_query=None):
"""Views entries."""
entries = Entry.select().order_by(Entry.timestamp.desc())
if search_query:
entries = entries.where(Entry.content.contains(search_query))
for entry in entries:
timestamp = entry.timestamp.strftime('%A %B %d, %Y %I: %M%p')
clear()
print(timestamp)
print("=" * len(timestamp))
print(entry.content)
print('\n\n' + '=' * len(timestamp))
print("n) next entry")
print("d) delete entry")
print("q) returnt to main menu")
next_action = input("Action: [n/d/q]: ").lower().strip()
if next_action == 'q':
break
elif next_action == 'd':
delete_entry(entry)
def search_entries():
"""Search entries for a term."""
view_entries(input("Search query: "))
def delete_entry(entry):
"""Deletes current entry."""
if input("Are you sure? [y/n]: ") == 'y':
entry.delete_instance()
print("Entry deleted!")
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
menu = OrderedDict([
('a', add_entry) ,
('v', view_entries) ,
('s', search_entries) ,
])
if __name__ == '__main__':
initialize()
menu_loop()
import sys
…
data = sys.stdin.read().strip()
Python comes with a library named SYS that relates to system functionality on your computer.
We’re gonna use the STDIN feature of that so we can capture an entry that has new lines in it.
entries.where(Entry.content.contains(search_query))
.contains is a method that lets you query against part of a string.
entry.timestamp.strftime(‘%A %B %d, %Y %I: %M%p’)
%A = Weekday, %B = Month, %d = Day, %Y = Year, %I = Hour, %M = Minute, %p = AM/PM.
entry.delete_instance()
This is how you delete an instance from a table.
import os
…
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
OS is a library, that allows us to call a program that works in the command line.
‘nt’ for Windows, ‘clear’ for Linux and Mac.