models.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. from flask import current_app
  2. from flaskbb.extensions import db
  3. def convert_to(value, value_type="text"):
  4. """Converts a value to a specified value type.
  5. Available value types are: string, int, boolean, list.
  6. A boolean type is handled as 0 for false and 1 for true.
  7. Raises a exception if the value couldn't be converted
  8. :param value: The value which should be converted.
  9. :param value_type: The value_type.
  10. """
  11. print "converting..."
  12. if value_type == "text":
  13. print "text %s" % value
  14. if isinstance(value, str):
  15. return value
  16. else:
  17. try:
  18. value = str(value)
  19. except ValueError:
  20. raise ValueError("Couldn't convert value to {}"
  21. .format(value_type))
  22. return value
  23. elif value_type == "int":
  24. print "int %s" % value
  25. try:
  26. value = int(value)
  27. except ValueError:
  28. raise ValueError("Couldn't convert value to {}"
  29. .format(value_type))
  30. print type(value)
  31. return value
  32. elif value_type == "boolean":
  33. try:
  34. value = int(value)
  35. if value < 0 or value > 1:
  36. raise ValueError("Value is not a boolean!. Value must be "
  37. "between 0 and 1.")
  38. else:
  39. return value
  40. except ValueError:
  41. raise ValueError("Couldn't convert value to {}"
  42. .format(value_type))
  43. class Settings(db.Model):
  44. __tablename__ = "settings"
  45. id = db.Column(db.Integer, primary_key=True)
  46. key = db.Column(db.String, unique=True)
  47. value = db.Column(db.String)
  48. # Available types: string, int, boolean
  49. value_type = db.Column(db.String)
  50. def save(self):
  51. db.session.add(self)
  52. db.session.commit()
  53. @classmethod
  54. def update(cls, configs):
  55. """Updates the current_app's config and stores the changes in the
  56. database.
  57. :param config: A dictionary with configuration items.
  58. """
  59. result = []
  60. updated_configs = {}
  61. for key, value in configs.iteritems():
  62. config = cls.query.filter(Settings.key == key.lower()).first()
  63. value = convert_to(value, config.value_type)
  64. config.value = value
  65. updated_configs[config.key.upper()] = config.value
  66. result.append(config)
  67. print "{}: {}".format(config.key, config.value)
  68. db.session.add(config)
  69. db.session.commit()
  70. print updated_configs
  71. current_app.config.update(updated_configs)
  72. @classmethod
  73. def get_all(cls):
  74. """Returns all settings as a dictionary
  75. The key is the same as in the config files.
  76. """
  77. settings = {}
  78. all_settings = cls.query.all()
  79. for setting in all_settings:
  80. settings[setting.key.upper()] = setting.value
  81. return settings