manage.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import argparse
  2. import sqlite3
  3. import uuid
  4. DB_FILENAME = "db.sqlite"
  5. SQL_CREATE_USERS = \
  6. """CREATE TABLE users (
  7. username TEXT PRIMARY KEY,
  8. api_key TEXT NOT NULL
  9. );"""
  10. SQL_CREATE_REQUESTS = \
  11. """CREATE TABLE requests (
  12. id TEXT PRIMARY KEY,
  13. username TEXT NOT NULL,
  14. depth INTEGER NOT NULL,
  15. width INTEGER NOT NULL,
  16. int_cycles INTEGER NOT NULL,
  17. ext_cycles INTEGER NOT NULL,
  18. status TEXT NOT NULL,
  19. FOREIGN KEY(username) REFERENCES users(username)
  20. );"""
  21. SQL_INSERT_USER = "INSERT INTO users VALUES('{username}', '{api_key}');"
  22. SQL_DELETE_USER = "DELETE FROM users WHERE username='{username}';"
  23. SQL_SELECT_USERS = "SELECT username, api_key FROM users;"
  24. conn = sqlite3.connect(DB_FILENAME)
  25. c = conn.cursor()
  26. def init_db():
  27. c.execute(SQL_CREATE_USERS)
  28. c.execute(SQL_CREATE_REQUESTS)
  29. def add_user(username):
  30. api_key = uuid.uuid4().hex
  31. sql = SQL_INSERT_USER.format(username=username, api_key=api_key)
  32. c.execute(sql)
  33. conn.commit()
  34. print("User '%s' added succesfully (api_key: %s)" % (username, api_key))
  35. def remove_user(username):
  36. sql = SQL_DELETE_USER.format(username=username)
  37. c.execute(sql)
  38. conn.commit()
  39. print("User '%s' removed succesfully from DB" % username)
  40. def list_users():
  41. c.execute(SQL_SELECT_USERS)
  42. for user, key in c.fetchall():
  43. print("%s\t%s" % (user, key))
  44. def parse_args():
  45. parser = argparse.ArgumentParser(
  46. description='Script to manage the DB related to the DEVStone comparative web service.')
  47. parser.add_argument('-i', '--init', action='store_true', help='Init the DB')
  48. parser.add_argument('-a', '--add_user', type=str, help='Add a user to the DB')
  49. parser.add_argument('-r', '--remove_user', type=str, help='Remove a user from the DB')
  50. parser.add_argument('-l', '--list_users', action='store_true', help='List existing users')
  51. return parser.parse_args()
  52. if __name__ == '__main__':
  53. args = parse_args()
  54. if args.init:
  55. init_db()
  56. if args.add_user:
  57. add_user(args.add_user)
  58. if args.remove_user:
  59. remove_user(args.remove_user)
  60. if args.list_users:
  61. list_users()