-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
73 lines (51 loc) · 1.94 KB
/
models.py
File metadata and controls
73 lines (51 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'''Datastore Models
Created on Mar 24, 2015
@author: prodonjs
'''
import calendar
import json
import re
import time
from google.appengine.api import memcache
from google.appengine.ext import ndb
#------------------------ Module variables and functions-----------------------
RE_URL_UNSAFE = re.compile(r'[^a-zA-Z0-9_\-.]+')
def make_url_safe(value, substitute):
"""Replaces unsafe URL characters with the provided substitute."""
return RE_URL_UNSAFE.sub(substitute, value).lower().strip(' ' + substitute)
class NdbModelEncoder(json.JSONEncoder):
def default(self, o):
"""Override default encoding for Model and Key objects."""
if isinstance(o, ndb.Model):
obj_dict = o.to_dict()
obj_dict['id'] = o.key.id()
return obj_dict
elif isinstance(o, ndb.Key):
return {'kind': o.kind(), 'id': o.id()}
else:
return super(NdbModelEncoder, self).default(o)
class TimestampedModel(ndb.Model):
created = ndb.IntegerProperty(indexed=True)
modified = ndb.IntegerProperty()
def _pre_put_hook(self):
"""Pre-put operations."""
now = calendar.timegm(time.gmtime())
self.modified = now
if not self.created:
self.created = now
class Topic(TimestampedModel):
"""Topic that can be voted on."""
name = ndb.StringProperty(required=True)
image = ndb.BlobProperty()
tags = ndb.StringProperty(repeated=True)
up_votes = ndb.IntegerProperty(required=True, default=0)
down_votes = ndb.IntegerProperty(required=True, default=0)
class Vote(ndb.Model):
"""User's vote on a particular Topic."""
topic = ndb.KeyProperty(Topic, required=True)
vote = ndb.StringProperty(required=True, choices=('up', 'down'))
class Profile(TimestampedModel):
"""User profile."""
avatar = ndb.BlobProperty()
topics = ndb.KeyProperty(Topic, repeated=True)
votes = ndb.StructuredProperty(Vote, repeated=True)