PageRenderTime 26ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/torneira/models/base.py

https://github.com/marcelnicolay/torneira
Python | 84 lines | 53 code | 17 blank | 14 comment | 9 complexity | 2c85334c7a40d23855559728dafa2dfa MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Licensed under the Open Software License ("OSL") v. 3.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.opensource.org/licenses/osl-3.0.php
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. import datetime
  16. from sqlalchemy import MetaData
  17. from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base
  18. from torneira.core.meta import TorneiraSession
  19. metadata = MetaData()
  20. class MetaBaseModel(DeclarativeMeta):
  21. def __init__(cls, classname, bases, dict_):
  22. return DeclarativeMeta.__init__(cls, classname, bases, dict_)
  23. Model = declarative_base(metadata=metadata, metaclass=MetaBaseModel)
  24. class Repository(object):
  25. def as_dict(self):
  26. items = {}
  27. for attrname in dir(self):
  28. if attrname.startswith("_"):
  29. continue
  30. attr = getattr(self, attrname)
  31. if isinstance(attr, (basestring, int, float, long)):
  32. items[attrname] = attr
  33. if isinstance(attr, (datetime.datetime, datetime.time)):
  34. items[attrname] = attr.isoformat()
  35. if isinstance(attr, list):
  36. items[attrname] = [x.as_dict() for x in attr]
  37. return items
  38. @classmethod
  39. def get(cls, id):
  40. session = TorneiraSession()
  41. return session.query(cls).get(id)
  42. @classmethod
  43. def fetch_by(cls, **kw):
  44. session = TorneiraSession()
  45. return session.query(cls).filter_by(**kw)
  46. @classmethod
  47. def all(cls, limit=None):
  48. session = TorneiraSession()
  49. if limit:
  50. return session.query(cls).all()[limit[0]:limit[1]]
  51. return session.query(cls).all()
  52. @classmethod
  53. def create(cls, **kwargs):
  54. instance = cls()
  55. for k, v in kwargs.items():
  56. setattr(instance, k, v)
  57. instance.save()
  58. return instance
  59. def delete(self):
  60. session = TorneiraSession()
  61. session.delete(self)
  62. session.flush()
  63. def save(self):
  64. session = TorneiraSession()
  65. if not self.id:
  66. session.add(self)
  67. session.flush()