75d3bd6 by Anon Ray at 2014-02-19 1
# coding utf-8
2
# classes/context.py
3
# class:: Context
4
5
from datetime import datetime
6
import json
7
cffc26d by Anon Ray at 2014-06-10 8
from sqlalchemy.exc import IntegrityError
9
75d3bd6 by Anon Ray at 2014-02-19 10
from swtstore.classes import db
11
from swtstore.classes.models.types import JSONType
12
from swtstore.classes.exceptions import AlreadyExistsError
13
14
15
class Context(db.Model):
16
    """ docstring """
17
18
    __tablename__ = 'contexts'
19
20
    id = db.Column(db.Integer, primary_key=True)
21
    name = db.Column(db.String(256), nullable=False, unique=True)
22
    definition = db.Column(JSONType, nullable=False)
23
    created = db.Column(db.DateTime, default=datetime.utcnow)
24
    modified = db.Column(db.DateTime, default=None)
25
d120774 by Anon Ray at 2014-03-08 26
    user_id = db.Column(db.ForeignKey('users.id'))
27
    creator = db.relationship('User')
28
29
    def __init__(self, name, definition, user_id):
75d3bd6 by Anon Ray at 2014-02-19 30
        for context in Context.query.all():
31
            if name == context.name:
32
                raise AlreadyExistsError('Context with name exists!')
33
                return
34
35
        self.name = name
36
        self.definition = definition
d120774 by Anon Ray at 2014-03-08 37
        self.user_id = user_id
75d3bd6 by Anon Ray at 2014-02-19 38
39
    def __repr__(self):
d120774 by Anon Ray at 2014-03-08 40
        return 'Context Object: <%s>' % self.name
75d3bd6 by Anon Ray at 2014-02-19 41
42
    def __str__(self):
43
        return 'Context Object: <%s>' % self.name
44
45
    def persist(self):
46
        db.session.add(self)
47
        try:
48
            db.session.commit()
49
        except IntegrityError:
50
            raise AlreadyExistsError('Error')
51
d120774 by Anon Ray at 2014-03-08 52
    def to_dict(self):
53
        return {
54
            'id': self.id,
55
            'name': self.name,
56
            'definition': json.dumps(self.definition),
57
            'created': self.created.isoformat(),
58
            'modified': self.modified
59
        }
60
75d3bd6 by Anon Ray at 2014-02-19 61
    # return a context instance given a name
62
    @staticmethod
8fe0bbc by Anon Ray at 2014-05-10 63
    def getByName(name):
75d3bd6 by Anon Ray at 2014-02-19 64
        return Context.query.filter_by(name=name).first()
65
d120774 by Anon Ray at 2014-03-08 66
    @staticmethod
67
    def getByCreator(id):
68
        return [each.to_dict() for each in Context.query.filter_by(user_id=id)]