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