Advertisement
ksieradzinski

Untitled

Jun 6th, 2025
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. from sys import argv
  2. import psycopg2
  3.  
  4. def init():
  5. connection = psycopg2.connect("dbname=todo user=postgres password=Password!")
  6. cursor = connection.cursor()
  7. cursor.execute("""
  8. CREATE TABLE todos (
  9. id SERIAL PRIMARY KEY,
  10. title TEXT NOT NULL,
  11. created_at TIMESTAMP DEFAULT NOW(),
  12. is_done BOOLEAN DEFAULT FALSE
  13. )
  14. """)
  15. connection.commit()
  16. connection.close()
  17.  
  18.  
  19. class TodoDB:
  20. def __init__(self, dsn:str):
  21. self.dsn = dsn
  22.  
  23. def connect(self):
  24. return psycopg2.connect(self.dsn)
  25.  
  26. def add_todo(self, title):
  27. with self.connect() as conn:
  28. cursor = conn.cursor()
  29. cursor.execute("INSERT INTO todos (title) VALUES(%s)", (title,))
  30. conn.commit()
  31.  
  32. def get_todos(self):
  33. with self.connect() as conn:
  34. cursor = conn.cursor()
  35. cursor.execute("SELECT id, title, created_at, is_done FROM todos order by created_at DESC")
  36. return cursor.fetchall()
  37.  
  38. def set_is_done(self, todo_id):
  39. with self.connect() as conn:
  40. cursor = conn.cursor()
  41. cursor.execute("UPDATE todos SET is_done=true WHERE id=%s", (todo_id,))
  42. conn.commit()
  43.  
  44. if len(argv) > 1 and argv[1] == "setup":
  45. init()
  46.  
  47.  
  48. database = TodoDB("dbname=todo user=postgres password=Password!")
  49. for todo_id, title, created_at, is_done in database.get_todos():
  50. if is_done:
  51. text_is_done = "✔️"
  52. else:
  53. text_is_done = "❌"
  54.  
  55. print(f"{text_is_done} Zadanie nr {todo_id}: {title}")
  56.  
  57. print("---" * 10)
  58. action = input("Co chcesz zrobić? d- dodaj, z - oznacz jako zrobione: ")
  59. if action == "d":
  60. title = input("Co masz do zrobienia? ")
  61. database.add_todo(title)
  62. elif action == "z":
  63. todo_id = int(input("Które zadanie zrobiłeś? "))
  64. database.set_is_done(todo_id)
  65. else:
  66. print("Niepoprawny wybór")
  67.  
  68.  
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement