Digitale bierlijst

seed.py 2.1KB

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