mysql.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. # coding: utf8
  2. import MySQLdb
  3. class noaMysql(object):
  4. def __init__(self, credentials):
  5. credentials['use_unicode'] = True
  6. self.__conn = MySQLdb.connect(**credentials)
  7. self.__swearwords = []
  8. self.__quotes = []
  9. self.__users = {
  10. "admin" : [],
  11. "moderator" : [],
  12. "privileged" : [],
  13. "default" : []
  14. }
  15. self.__loadData()
  16. def __loadData(self):
  17. """
  18. Get data from MySQL tables
  19. """
  20. #Load users privileges
  21. cursor = self.__conn.cursor(MySQLdb.cursors.DictCursor)
  22. cursor.execute("SELECT * FROM users")
  23. for row in cursor.fetchall():
  24. self.__users[row['role']].append(row['nickname'])
  25. # Load swearwords
  26. cursor.execute("SELECT * FROM swearwords")
  27. for row in cursor.fetchall():
  28. self.__swearwords.append(row['swearword'])
  29. # Load quotes
  30. cursor = self.__conn.cursor(MySQLdb.cursors.DictCursor)
  31. cursor.execute("SELECT * FROM quotes")
  32. for row in cursor.fetchall():
  33. self.__quotes.append(row['quote'])
  34. #######################################
  35. def addSwearword(self, swearword):
  36. """
  37. Append a new swearword into database
  38. """
  39. cursor = self.__conn.cursor()
  40. cursor.execute('INSERT INTO swearwords (swearword) VALUES("%s")' % (swearword))
  41. self.__conn.commit()
  42. self.__swearwords.append(swearword)
  43. def getSwearwords(self):
  44. """
  45. Returns ban words
  46. """
  47. return self.__swearwords
  48. def delSwearword(self, swearword):
  49. """
  50. Remove ban word from database
  51. """
  52. try:
  53. index = self.__swearwords.index(swearword)
  54. except ValueError:
  55. return None
  56. cursor = self.__conn.cursor()
  57. cursor.execute('DELETE FROM swearwords WHERE swearword = "%s"' % (swearword))
  58. self.__conn.commit()
  59. del self.__swearwords[index]
  60. return index
  61. #######################################
  62. def addQuote(self, quote):
  63. """
  64. Append a new swearword into database
  65. """
  66. cursor = self.__conn.cursor()
  67. cursor.execute('INSERT INTO quotes (quote) VALUES("%s")' % (quote))
  68. self.__conn.commit()
  69. self.__quotes.append(quote)
  70. def getQuote(self, index):
  71. """
  72. Returns quotes
  73. """
  74. try:
  75. return self.__quotes[index]
  76. except IndexError:
  77. return None
  78. #######################################
  79. def getUsers(self):
  80. """
  81. Return users
  82. """
  83. return self.__users