main.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python3
  2. import sqlite3
  3. from pathlib import Path
  4. from typing import Any, Dict
  5. from nicegui import ui
  6. DB_FILE = Path(__file__).parent / 'users.db'
  7. DB_FILE.touch()
  8. conn = sqlite3.connect(DB_FILE, check_same_thread=False)
  9. cursor = conn.cursor()
  10. cursor.execute('CREATE TABLE IF NOT EXISTS users (id integer primary key AUTOINCREMENT, name text, age integer)')
  11. conn.commit()
  12. @ui.refreshable
  13. def users_ui() -> None:
  14. cursor.execute('SELECT * FROM users')
  15. for row in cursor.fetchall():
  16. user = {'id': row[0], 'name': row[1], 'age': row[2]}
  17. with ui.card():
  18. with ui.row().classes('justify-between w-full'):
  19. ui.label(user['id'])
  20. ui.label(user['name'])
  21. ui.label(user['age'])
  22. with ui.row():
  23. ui.button('edit', on_click=lambda user=user: open_dialog(user))
  24. ui.button('delete', on_click=lambda user=user: delete(user), color='red')
  25. def create() -> None:
  26. cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', (name.value, age.value))
  27. conn.commit()
  28. ui.notify(f'Created new user {name.value}')
  29. name.value = ''
  30. age.value = None
  31. users_ui.refresh()
  32. def update() -> None:
  33. query = 'UPDATE users SET name=?, age=? WHERE id=?'
  34. cursor.execute(query, (dialog_name.value, dialog_age.value, dialog_id))
  35. conn.commit()
  36. ui.notify(f'Updated user {dialog_name.value}')
  37. dialog.close()
  38. users_ui.refresh()
  39. def delete(user: Dict[str, Any]) -> None:
  40. cursor.execute('DELETE from users WHERE id=?', (user['id'],))
  41. conn.commit()
  42. ui.notify(f'Deleted user {user["name"]}')
  43. users_ui.refresh()
  44. def open_dialog(user: Dict[str, Any]) -> None:
  45. global dialog_id
  46. dialog_id = user['id']
  47. dialog_name.value = user['name']
  48. dialog_age.value = user['age']
  49. dialog.open()
  50. name = ui.input(label='Name')
  51. age = ui.number(label='Age', format='%.0f')
  52. ui.button('Add new user', on_click=create)
  53. users_ui()
  54. with ui.dialog() as dialog:
  55. with ui.card():
  56. dialog_id = None
  57. dialog_name = ui.input('Name')
  58. dialog_age = ui.number('Age', format='%.0f')
  59. with ui.row():
  60. ui.button('Save', on_click=update)
  61. ui.button('Close', on_click=dialog.close).props('outline')
  62. ui.run()