home · contact · privacy
Adapt tests to new cache emptying reality.
[plomtask] / run.py
1 #!/usr/bin/env python3
2 """Call this to start the application."""
3 from sys import exit as sys_exit
4 from os import environ
5 from plomtask.exceptions import HandledException, NotFoundException
6 from plomtask.http import TaskHandler, TaskServer
7 from plomtask.db import DatabaseFile, UnmigratedDbException
8
9 PLOMTASK_DB_PATH = environ.get('PLOMTASK_DB_PATH')
10 HTTP_PORT = 8082
11 DB_CREATION_ASK = 'Database file not found. Create? Y/n\n'
12 DB_MIGRATE_ASK = 'Database file needs migration. Migrate? Y/n\n'
13
14
15 def yes_or_fail(question: str, fail_msg: str) -> None:
16     """Ask question, raise HandledException(fail_msg) if reply not yes."""
17     reply = input(question)
18     if not reply.lower() in {'y', 'yes', 'yes.', 'yes!'}:
19         print('Not recognizing reply as "yes".')
20         raise HandledException(fail_msg)
21
22
23 if __name__ == '__main__':
24     try:
25         if not PLOMTASK_DB_PATH:
26             raise HandledException('PLOMTASK_DB_PATH not set.')
27         try:
28             db_file = DatabaseFile(PLOMTASK_DB_PATH)
29         except NotFoundException:
30             yes_or_fail(DB_CREATION_ASK, 'Cannot run without DB.')
31             db_file = DatabaseFile.create_at(PLOMTASK_DB_PATH)
32         except UnmigratedDbException:
33             yes_or_fail(DB_MIGRATE_ASK, 'Cannot run with unmigrated DB.')
34             db_file = DatabaseFile.migrate(PLOMTASK_DB_PATH)
35         server = TaskServer(db_file, ('localhost', HTTP_PORT), TaskHandler)
36         print(f'running at port {HTTP_PORT}')
37         try:
38             server.serve_forever()
39         except KeyboardInterrupt:
40             print('aborting due to keyboard interrupt')
41         server.server_close()
42     except HandledException as e:
43         print(f'Aborting because: {e}')
44         sys_exit(1)