Digitale bierlijst

seed.py 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """
  2. Provides functions to manage the database while the server is offline.
  3. """
  4. import argparse
  5. import csv
  6. import os
  7. from piket_server import db, Person, Settlement, ConsumptionType, Consumption
  8. def main():
  9. """ Main entry point. """
  10. parser = argparse.ArgumentParser()
  11. subparsers = parser.add_subparsers()
  12. # Clear command
  13. parser_clear = subparsers.add_parser("clear", help="Clear the database.")
  14. parser_clear.set_defaults(func=cmd_clear)
  15. parser_clear.add_argument("--removemydata", action="store_true")
  16. # Parser load_seeds
  17. parser_load_persons = subparsers.add_parser(
  18. "load_persons", help="Load Person data."
  19. )
  20. parser_load_persons.set_defaults(func=cmd_load_persons)
  21. parser_load_persons.add_argument("datafile")
  22. args = parser.parse_args()
  23. args.func(args)
  24. def cmd_clear(args) -> None:
  25. """ Entry point for 'clear' subcommand. """
  26. if not args.removemydata:
  27. print("WARNING! This command will delete all contents in your database!")
  28. print("Type 'removemydata' to continue, anything else or CTRL-C to abort.")
  29. confirmation = input("> ")
  30. do_wipe = confirmation == "removemydata"
  31. else:
  32. do_wipe = True
  33. if do_wipe:
  34. print("Dropping all tables...")
  35. db.drop_all()
  36. print("All data removed. Recreating database...")
  37. db.create_all()
  38. from alembic.config import Config
  39. from alembic import command
  40. alembic_cfg = Config(os.path.join(os.path.dirname(__file__), "alembic.ini"))
  41. command.stamp(alembic_cfg, "head")
  42. print("Done.")
  43. return
  44. print("Aborting.")
  45. def cmd_load_persons(args) -> None:
  46. """ Entrypoint for 'load_persons" subcommand. """
  47. print("Loading persons.")
  48. with open(args.datafile) as csvfile:
  49. reader = csv.DictReader(csvfile)
  50. for row in reader:
  51. p = Person(name=row["name"], active=bool(int(row["active"])))
  52. db.session.add(p)
  53. db.session.commit()
  54. print("Done.")
  55. if __name__ == "__main__":
  56. main()