You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.4KB

  1. from models.database import db
  2. import mysql.connector
  3. def get_user(username):
  4. """
  5. Get the user with the given username
  6. :param username: The username
  7. :type username: str
  8. :return: user
  9. """
  10. db.connect()
  11. cursor = db.cursor()
  12. query = ("SELECT userid, username, password from users where username = %s")
  13. user = None
  14. try:
  15. cursor.execute(query, (username,))
  16. users = cursor.fetchall()
  17. if len(users):
  18. user = users[0]
  19. except mysql.connector.Error as err:
  20. print("Failed executing query: {}".format(err))
  21. cursor.fetchall()
  22. exit(1)
  23. finally:
  24. cursor.close()
  25. db.close()
  26. return user
  27. def get_users():
  28. """
  29. Retreive all registrered users from the database
  30. :return: users
  31. """
  32. db.connect()
  33. cursor = db.cursor()
  34. query = ("SELECT userid, username from users")
  35. try:
  36. cursor.execute(query)
  37. users = cursor.fetchall()
  38. except mysql.connector.Error as err:
  39. print("Failed executing query: {}".format(err))
  40. users = []
  41. cursor.fetchall()
  42. exit(1)
  43. finally:
  44. cursor.close()
  45. db.close()
  46. return users
  47. def get_user_id_by_name(username):
  48. """
  49. Get the id of the unique username
  50. :param username: Name of the user
  51. :return: The id of the user
  52. """
  53. db.connect()
  54. cursor = db.cursor()
  55. query = ("SELECT userid from users WHERE username = %s")
  56. userid = None
  57. try:
  58. cursor.execute(query, (username,))
  59. users = cursor.fetchall()
  60. if(len(users)):
  61. userid = users[0][0]
  62. except mysql.connector.Error as err:
  63. print("Failed executing query: {}".format(err))
  64. cursor.fetchall()
  65. exit(1)
  66. finally:
  67. cursor.close()
  68. db.close()
  69. return userid
  70. def get_user_name_by_id(userid):
  71. """
  72. Get username from user id
  73. :param userid: The id of the user
  74. :return: The name of the user
  75. """
  76. db.connect()
  77. cursor = db.cursor()
  78. query = ("SELECT username from users WHERE userid = %s")
  79. username = None
  80. try:
  81. cursor.execute(query, (userid,))
  82. users = cursor.fetchall()
  83. if len(users):
  84. username = users[0][0]
  85. except mysql.connector.Error as err:
  86. print("Failed executing query: {}".format(err))
  87. cursor.fetchall()
  88. exit(1)
  89. finally:
  90. cursor.close()
  91. db.close()
  92. return username