Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
My First App
#8
This is the newest app. I think this one will hopefully work a little better.

main.py:
import datetime
import questionary
from db import HabitDB
from habit import Habit

def main():
    while True:
        choices = [
            {'name': 'Create a habit', 'value': create_habit},
            {'name': 'List habits', 'value': list_habits},
            {'name': 'Mark habit complete', 'value': mark_complete},
            {'name': 'Mark habit incomplete', 'value': mark_incomplete},
            {'name': 'Delete a habit', 'value': delete_habit},
            {'name': 'Exit', 'value': exit}
        ]
        choice = questionary.select('What would you like to do?', choices=choices).ask()

        if choice:
            choice()

def create_habit():
    name = questionary.text('Enter the name of the habit:').ask()
    frequency = questionary.select('How often should this habit be completed?', choices=['daily', 'weekly', 'monthly']).ask()
    completed = False
    habit = HabitDB(name, frequency)
    habit.save()
    print(f'Habit "{name}" with frequency "{frequency}" created successfully!')

def list_habits():
    habits = Habit.list_all()
    for habit in habits:
        print(f'{habit.name} ({habit.frequency} days) - {"Complete" if habit.completed else "Incomplete"}')

def mark_complete():
    habits = Habit.list_all()
    habit_choices = [{'name': habit.name, 'value': habit} for habit in habits]
    habit = questionary.select('Which habit would you like to mark as complete?', choices=habit_choices).ask()
    habit.mark_complete()
    print(f'Habit "{habit.name}" marked as complete!')

def mark_incomplete():
    habits = Habit.list_all()
    habit_choices = [{'name': habit.name, 'value': habit} for habit in habits]
    habit = questionary.select('Which habit would you like to mark as incomplete?', choices=habit_choices).ask()
    habit.mark_incomplete()
    print(f'Habit "{habit.name}" marked as incomplete!')

def delete_habit():
    habits = Habit.list_all()
    habit_choices = [{'name': habit.name, 'value': habit} for habit in habits]
    habit = questionary.select('Which habit would you like to delete?', choices=habit_choices).ask()
    habit.delete()
    print(f'Habit "{habit.name}" deleted successfully!')

if __name__ == '__main__':
    main()
db.py:
import sqlite3
from datetime import datetime
from habit import Habit

class HabitDB:
    def __init__(self, name, frequency):
        self.name = name
        self.frequency = frequency
        self.completed = []
        
    
    def mark_complete(self):
        today = datetime.date.today()
        self.completed.append(today)

    def is_complete(self):
        if self.frequency == 'daily':
            return datetime.date.today() in self.completed
        elif self.frequency == 'weekly':
            start_of_week = (datetime.date.today() - datetime.timedelta(days=datetime.date.today().weekday()))
            end_of_week = start_of_week + datetime.timedelta(days=6)
            for day in range((end_of_week - start_of_week).days + 1):
                date = start_of_week + datetime.timedelta(days=day)
                if date in self.completed:
                    return True
            return False
        elif self.frequency == 'monthly':
            today = datetime.date.today()
            if today.day >= 28:
                end_of_month = today.replace(day=28) + datetime.timedelta(days=4)
                for day in range((end_of_month - today).days + 1):
                    date = today + datetime.timedelta(days=day)
                    if date in self.completed:
                        return True
                return False
            else:
                return today.replace(day=1) in self.completed

    def delete(self):
        with sqlite3.connect('habits.db') as conn:
            cursor = conn.cursor()
            cursor.execute('DELETE FROM habits WHERE name = ?', (self.name,))

    @staticmethod
    def list_by_frequency(frequency):
        with sqlite3.connect('habits.db') as conn:
            cursor = conn.cursor()
            cursor.execute('SELECT name FROM habits WHERE frequency = ?', (frequency,))
            return [row[0] for row in cursor.fetchall()]

    def save(self):
        with sqlite3.connect('habits.db') as conn:
            cursor = conn.cursor()
            cursor.execute('INSERT INTO habits (name, frequency, completed) VALUES (?, ?, ?)', (self.name, str(self.frequency), self.completed))


    def update(self):
        with sqlite3.connect('habits.db') as conn:
            cursor = conn.cursor()
            cursor.execute('UPDATE habits SET completed = ? WHERE name = ?', (self.completed, self.name))

    @staticmethod
    def get_all_habits():
        with sqlite3.connect('habits.db') as conn:
            cursor = conn.cursor()
            cursor.execute('SELECT name, frequency, completed FROM habits')
            rows = cursor.fetchall()
            habits = []
            for row in rows:
                habit = Habit(row[0], row[1])
                habit.completed = [datetime.date.fromisoformat(date_str) for date_str in row[2].split(',')]
                habits.append(habit)
            return habits

def create_table():
    with sqlite3.connect('habits.db') as conn:
        cursor = conn.cursor()
        cursor.execute('''CREATE TABLE IF NOT EXISTS habits
                          (name TEXT PRIMARY KEY, frequency TEXT, completed TEXT)''')
habit.py:
from datetime import datetime, date

class Habit:
    def __init__(self, name, frequency):
        self.name = name
        self.frequency = frequency
        self.completed = []

    def mark_complete(self):
        today = datetime.now()
        self.completed.append(today)
        
    def mark_incomplete(self):
        today = datetime.now()
        self.completed.remove(today)
        

    def is_complete(self):
        if self.frequency == 'daily':
            return datetime.now() in self.completed
        elif self.frequency == 'weekly':
            start_of_week = (datetime.date.now() - datetime.timedelta(days=datetime.now().weekday()))
            end_of_week = start_of_week + datetime.timedelta(days=6)
            for day in range((end_of_week - start_of_week).days + 1):
                date = start_of_week + datetime.timedelta(days=day)
                if date in self.completed:
                    return True
            return False
        elif self.frequency == 'monthly':
            today = datetime.now()
            if today.day >= 28:
                end_of_month = today.replace(day=28) + datetime.timedelta(days=4)
                for day in range((end_of_month - today).days + 1):
                    date = today + datetime.timedelta(days=day)
                    if date in self.completed:
                        return True
                return False
            else:
                return today.replace(day=1) in self.completed

    def delete(self):
        del self
        

    @staticmethod
    def list_by_frequency(habits, frequency):
        result = []
        for habit in habits:
            if habit.frequency == frequency:
                result.append(habit.name)
        return result
    
    def list_all(habits):
        result = []
        for habit in habits:
            result.append(habit.name)
        return result
    
    
Reply


Messages In This Thread
My First App - by BCopeland64 - Feb-13-2023, 09:18 AM
RE: My First App - by buran - Feb-15-2023, 11:57 AM
RE: My First App - by BCopeland64 - Feb-15-2023, 05:46 PM
RE: My First App - by buran - Feb-15-2023, 07:21 PM
RE: My First App - by BCopeland64 - Feb-16-2023, 09:20 AM
RE: My First App - by buran - Feb-16-2023, 11:20 AM
RE: My First App - by BCopeland64 - Feb-16-2023, 11:52 AM
RE: My First App - by BCopeland64 - Feb-16-2023, 08:20 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020