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.

136 line
4.2KB

  1. import sqlite3
  2. import os
  3. from flask import json, g
  4. db_root=os.getenv("DB_ROOT", "")
  5. db_location=db_root + '/craftbeerpi.db'
  6. def get_db():
  7. db = getattr(g, '_database', None)
  8. if db is None:
  9. def dict_factory(cursor, row):
  10. d = {}
  11. for idx, col in enumerate(cursor.description):
  12. d[col[0]] = row[idx]
  13. return d
  14. db = g._database = sqlite3.connect(db_location)
  15. db.row_factory = dict_factory
  16. return db
  17. class DBModel(object):
  18. __priamry_key__ = "id"
  19. __as_array__ = False
  20. __order_by__ = None
  21. __json_fields__ = []
  22. def __init__(self, args):
  23. self.__setattr__(self.__priamry_key__, args.get(self.__priamry_key__))
  24. for f in self.__fields__:
  25. if f in self.__json_fields__:
  26. if args.get(f) is not None:
  27. if isinstance(args.get(f) , dict) or isinstance(args.get(f) , list) :
  28. self.__setattr__(f, args.get(f))
  29. else:
  30. self.__setattr__(f, json.loads(args.get(f)))
  31. else:
  32. self.__setattr__(f, None)
  33. else:
  34. self.__setattr__(f, args.get(f))
  35. @classmethod
  36. def get_all(cls):
  37. cur = get_db().cursor()
  38. if cls.__order_by__ is not None:
  39. cur.execute("SELECT * FROM %s ORDER BY %s.'%s'" % (cls.__table_name__,cls.__table_name__,cls.__order_by__))
  40. else:
  41. cur.execute("SELECT * FROM %s" % cls.__table_name__)
  42. if cls.__as_array__ is True:
  43. result = []
  44. for r in cur.fetchall():
  45. result.append( cls(r))
  46. else:
  47. result = {}
  48. for r in cur.fetchall():
  49. result[r.get(cls.__priamry_key__)] = cls(r)
  50. return result
  51. @classmethod
  52. def get_one(cls, id):
  53. cur = get_db().cursor()
  54. cur.execute("SELECT * FROM %s WHERE %s = ?" % (cls.__table_name__, cls.__priamry_key__), (id,))
  55. r = cur.fetchone()
  56. if r is not None:
  57. return cls(r)
  58. else:
  59. return None
  60. @classmethod
  61. def delete(cls, id):
  62. cur = get_db().cursor()
  63. cur.execute("DELETE FROM %s WHERE %s = ? " % (cls.__table_name__, cls.__priamry_key__), (id,))
  64. get_db().commit()
  65. @classmethod
  66. def insert(cls, **kwargs):
  67. cur = get_db().cursor()
  68. if cls.__priamry_key__ is not None and kwargs.has_key(cls.__priamry_key__):
  69. query = "INSERT INTO %s (%s, %s) VALUES (?, %s)" % (
  70. cls.__table_name__,
  71. cls.__priamry_key__,
  72. ', '.join("'%s'" % str(x) for x in cls.__fields__),
  73. ', '.join(['?'] * len(cls.__fields__)))
  74. data = ()
  75. data = data + (kwargs.get(cls.__priamry_key__),)
  76. for f in cls.__fields__:
  77. if f in cls.__json_fields__:
  78. data = data + (json.dumps(kwargs.get(f)),)
  79. else:
  80. data = data + (kwargs.get(f),)
  81. else:
  82. query = 'INSERT INTO %s (%s) VALUES (%s)' % (
  83. cls.__table_name__,
  84. ', '.join("'%s'" % str(x) for x in cls.__fields__),
  85. ', '.join(['?'] * len(cls.__fields__)))
  86. data = ()
  87. for f in cls.__fields__:
  88. if f in cls.__json_fields__:
  89. data = data + (json.dumps(kwargs.get(f)),)
  90. else:
  91. data = data + (kwargs.get(f),)
  92. cur.execute(query, data)
  93. get_db().commit()
  94. i = cur.lastrowid
  95. kwargs["id"] = i
  96. return cls(kwargs)
  97. @classmethod
  98. def update(cls, **kwargs):
  99. cur = get_db().cursor()
  100. query = 'UPDATE %s SET %s WHERE %s = ?' % (
  101. cls.__table_name__,
  102. ', '.join("'%s' = ?" % str(x) for x in cls.__fields__),cls.__priamry_key__)
  103. data = ()
  104. for f in cls.__fields__:
  105. if f in cls.__json_fields__:
  106. data = data + (json.dumps(kwargs.get(f)),)
  107. else:
  108. data = data + (kwargs.get(f),)
  109. data = data + (kwargs.get(cls.__priamry_key__),)
  110. cur.execute(query, data)
  111. get_db().commit()
  112. return cls(kwargs)