class Group(ndb.Expando): name = ndb.StringProperty(indexed=True, required=True)# content = ndb.StringProperty() parent_group = ndb.StringProperty() #user could be only at one of this group #if parent_group == parent group admin... could same capabilities #key_value = ndb.StringProperty(indexed=True) #Key prop history = ndb.JsonProperty() role = ndb.JsonProperty() #mail = ndb.StringProperty() in_group = ndb.IntegerProperty(default=0) #creator_mail = ndb.StringProperty() #?? if it in key == ancestore #is_open = ndb.BooleanProperty(default=False) #invite = ndb.StringProperty() photo_list = ndb.StringProperty(repeated=True) #{val[], def[], kind - json, opt} stats = ndb.JsonProperty(default={'st_name':[], 'value':[], 'opt':[]}) stats_private = ndb.JsonProperty(default={'st_name':[], 'value':[], 'opt':[]}) #only in this group access # only for private, rate st_w = ndb.JsonProperty(default=[]) #Summarise rankings st_place = ndb.JsonProperty() #different options for compute poits #0 - current, 1/2 - foward/backward sort + 1/x role_propertys = ndb.JsonProperty(default = { "admin":{"change":[], "visible":[]}, "user":{"change":["@name"], #Only own "visible":[]}, "__creator":{"change":['@invite'], "visible":[]}, "__id":{"change":['@invite'], "visible":[]} }) ask_join = ndb.JsonProperty(default={}) #url:[mail,role,mess] joined = ndb.JsonProperty(default=[]) #url ban = ndb.JsonProperty(default=[]) #mail invite = ndb.JsonProperty(default={}) #mail chat = ndb.TextProperty() rate = ndb.FloatProperty(repeated=True) top_rate = ndb.JsonProperty(default=[]) #top 3 obj down this group [[avt, n, rate, url, kind], [],[]] frame = ndb.StringProperty(repeated=True) # history mark if obj in top3 free = ndb.BooleanProperty(default=False) #anybody can add to group public_view = ndb.BooleanProperty(default=False) #avary body could see ??add @open_view
class Jobs(ndb.Model): client = ndb.KeyProperty(indexed=True) client_rating = ndb.StructuredProperty(Rate, indexed=False) address = ndb.StringProperty(indexed=False) handyman = ndb.KeyProperty(indexed=True) handy_rating = ndb.StructuredProperty(Rate, indexed=False) messages = ndb.StructuredProperty(Messages, repeated=True) scheduled = ndb.DateTimeProperty(indexed=False, auto_now=True) completed = ndb.DateTimeProperty(indexed=True, auto_now=True) labor = ndb.FloatProperty(indexed=False) supplies = ndb.FloatProperty(indexed=False) discount = ndb.FloatProperty(indexed=False) tax = ndb.FloatProperty(indexed=False) earning = ndb.FloatProperty(indexed=False) tip = ndb.FloatProperty(indexed=False)
class User(ndb.Model): """User profile""" name = ndb.StringProperty(required=True) email = ndb.StringProperty(required=False) wins = ndb.IntegerProperty(default=0) losses = ndb.IntegerProperty(default=0) games_behind = ndb.IntegerProperty(default=0) games = ndb.IntegerProperty(default=0) win_ratio = ndb.FloatProperty(default=0) # scoreboard output def to_form(self): """Returns Users results - all completed games, wins and losses""" form = UserScoreForm() form.player = self.name form.games_played = self.games form.wins = self.wins form.losses = self.losses form.win_ratio = self.win_ratio return form
class User(ndb.Model): """User profile""" name = ndb.StringProperty(required=True) email = ndb.StringProperty() average_attempts = ndb.FloatProperty(default=float('inf')) @classmethod def get_top_users(cls, limit): """Return top n users, n = limit""" return User.query().order(User.average_attempts).fetch(limit) def to_form(self): """Returns a UserAverageForm representation of the User""" form = UserAverageForm() form.user_name = self.name form.email = self.email if self.average_attempts == float('inf'): form.average_attempts = 'No game is finished.' else: form.average_attempts = str(self.average_attempts) return form
class GlobalStats(NdbModel): NAMESPACE = NAMESPACE name = ndb.StringProperty() token_count = ndb.IntegerProperty() unlocked_count = ndb.IntegerProperty() value = ndb.FloatProperty() # Value in dollar # Value per other currency currencies = ndb.LocalStructuredProperty(CurrencyValue, repeated=True) # type: list[CurrencyValue] market_cap = ndb.ComputedProperty(lambda self: (self.value or 0) * self.unlocked_count, indexed=False) @property def id(self): return self.key.id().decode('utf-8') @classmethod def create_key(cls, currency): return ndb.Key(cls, currency, namespace=NAMESPACE) @classmethod def list(cls): return cls.query()
class HskText(ndb.Model): """Models a Chinese text entry with HSK annotation. u_content : content must be already encoded in utf-8 """ u_content = ndb.TextProperty() u_annotation = ndb.TextProperty() totalhskcount = ndb.IntegerProperty() hsk1percentage = ndb.FloatProperty() hsk2percentage = ndb.FloatProperty() hsk3percentage = ndb.FloatProperty() hsk4percentage = ndb.FloatProperty() hsk5percentage = ndb.FloatProperty() hsk6percentage = ndb.FloatProperty() address = ndb.StringProperty() date = ndb.DateTimeProperty(auto_now_add=True)
class User(ndb.Model): """User profile""" name = ndb.StringProperty(required=True) email = ndb.StringProperty() won = ndb.IntegerProperty(default=0) total_played = ndb.IntegerProperty(default=0) win_ratio = ndb.FloatProperty(default=0.0) def to_form(self): """Returns a UserForm representation of the User. Args: None. Returns: UserForm: Form representation of the user. """ form = UserForm() form.name = self.name form.email = self.email form.won = self.won form.total_played = self.total_played form.win_ratio = self.win_ratio return form
class StopTime(CsvModel): class PickupDropoffType(messages.Enum): AVAILABLE = 0 UNAVAILABLE = 1 SCHEDULE_WITH_AGENCY = 2 SCHEDULE_WITH_DRIVER = 3 class TimePoint(messages.Enum): APPROXIMATE = 0 EXACT = 1 _csv_file = 'stop_times.txt' _csv_parent_id = 'trip_id' _csv_list_index = 'stop_sequence' arrival_time = ndb.StringProperty() departure_time = ndb.StringProperty() stop_id = ndb.KeyProperty(kind='Stop', required=True) stop_headsign = ndb.StringProperty() pickup_type = msgprop.EnumProperty(PickupDropoffType) drop_off_type = msgprop.EnumProperty(PickupDropoffType) shape_dist_traveled = ndb.FloatProperty() timepoint = msgprop.EnumProperty(TimePoint)
class Comment(ndb.Model): created = ndb.DateTimeProperty(auto_now_add=True) user_id = ndb.StringProperty(required=True) username = ndb.StringProperty(required=True) post_id = ndb.StringProperty(required=True) comment = ndb.StringProperty( required=True) # Maximum length of a comment = 1500 bytes score = ndb.StringProperty(required=True) total_score = ndb.FloatProperty(required=True) no_scored = ndb.IntegerProperty(required=True) def as_dict(self): time_fmt = '%c' d = { 'user_id': self.user_id, 'username': self.username, 'post_id': self.post_id, 'created': self.created.strftime(time_fmt), 'comment': self.comment, 'score': self.score } return d
class PantryItem(ndb.Model): """A model for representing a food item""" """ _parent = None # Special part to specific protorpc fields _message_fields_schema = ('id', 'parent', 'food', 'initial_quantity', 'initial_quantity_unit', 'percent_remaining', 'start_date', 'expiration_date') """ food = ndb.StructuredProperty(Food) initial_quantity = ndb.FloatProperty() initial_quantity_unit = ndb.StringProperty(choices=('g', 'ml')) percent_remaining = ndb.IntegerProperty(validator=percent_validator) start_date = ndb.DateProperty(auto_now_add=True) expiration_date = ndb.DateProperty() def set_expiration_date(self, date=None): if not date: self.expiration_date = (self.start_date + timedelta(days=self.food.lasts_days)) else: self.expiration_date = date
class Event(EventBase): """ An individual event. """ event_id = ndb.StringProperty(indexed=False) datetime = ndb.DateTimeProperty(auto_now=True, indexed=True) time_spent = ndb.FloatProperty(indexed=False) data = ndb.JsonProperty() server_name = ndb.StringProperty() site = ndb.StringProperty() def serialize(self): data = {} data['id'] = self.event_id data['checksum'] = self.checksum data['project'] = self.project data['logger'] = self.logger data['level'] = self.get_level_display() data['culprit'] = self.culprit for k, v in sorted(self.data.iteritems()): data[k] = v return data
class ChangeLine(ndb.Model): """Single change line""" year = ndb.IntegerProperty() leading_item = ndb.IntegerProperty() req_code = ndb.IntegerProperty() req_title = ndb.StringProperty() change_code = ndb.IntegerProperty() change_title = ndb.StringProperty() change_type_id = ndb.IntegerProperty() change_type_name = ndb.StringProperty() committee_id = ndb.IntegerProperty() budget_code = ndb.StringProperty() budget_title = ndb.StringProperty() net_expense_diff = ndb.IntegerProperty() gross_expense_diff = ndb.IntegerProperty() allocated_income_diff = ndb.IntegerProperty() commitment_limit_diff = ndb.IntegerProperty() personnel_max_diff = ndb.FloatProperty() date = ndb.DateProperty() explanation = ndb.TextProperty(indexed=False) prefixes = ndb.StringProperty(repeated=True)
class Entry(ndb.Model): # Need to set Account as the parent of every entry date = ndb.DateProperty(required = True) datakind = ndb.StringProperty(choices = ["work", "event"], indexed = False) isAchievement = ndb.BooleanProperty(default = False) #indexed notes = ndb.TextProperty() tags = ndb.StringProperty(repeated = True, indexed = False) # normalized tags eg. "App Engine" --> "appengine" - computed property normtags = ndb.ComputedProperty(lambda self: self._normalize_tags(), repeated = True) project = ndb.KeyProperty(Projects) projectName = ndb.StringProperty(indexed = False) #isWorkProductive = ndb.BooleanProperty(indexed = False) hoursWorked = ndb.FloatProperty(indexed = False) def _normalize_tags(self): tags = self.tags first_level = [t.lower().replace(' ', '') for t in tags] # hajj house as hajjhouse #second_level = [] # 'hajj house' as 'hajj' and 'house' #for tag in tags: # second_level += [t.lower() for t in tag.split(' ') if t] return first_level# + second_level
class HitModule(ndb.Model): status = ndb.IntegerProperty(choices=STATUS_CHOICES, default=STATUS_AVAILABLE) consider_days = ndb.IntegerProperty(default=30) items = ndb.KeyProperty(kind=MenuItem, repeated=True) cunning_items = ndb.KeyProperty(kind=MenuItem, repeated=True) max_item_amount = ndb.IntegerProperty(default=10) min_item_rating = ndb.FloatProperty(default=0) title = ndb.StringProperty(default=u'Хиты') picture = ndb.StringProperty() def get_items(self): items = [] for item in self.items: item = item.get() item.sequence_number = int((1.0 - item.rating) * 100) if item.status == STATUS_UNAVAILABLE: continue if item.status == STATUS_UNAVAILABLE: continue items.append(item) return items
class PatientProfile(ndb.Model): """A main model for representing an individual Patient entry.""" hospitalStaff = ndb.StructuredProperty(HospitalStaff) # Profile information name = ndb.StringProperty() nric_num = ndb.StringProperty() gender = ndb.StringProperty(indexed=False, choices=set(["male", "female"])) nationality = ndb.StringProperty(indexed=False) dob = ndb.StringProperty(indexed=False) race = ndb.StringProperty(indexed=False) mobile_number = ndb.StringProperty(indexed=False) address = ndb.StringProperty(indexed=False) add_info = ndb.StringProperty(indexed=False) # Triage Readings temperature = ndb.FloatProperty(indexed=False, default=0) heart_rate = ndb.IntegerProperty(indexed=False, default=0) bp = ndb.IntegerProperty(indexed=False, default=0) respo_rate = ndb.IntegerProperty(indexed=False, default=0) date = ndb.DateTimeProperty(auto_now_add=True) travel_history = ndb.StringProperty(indexed=False) chief_complaint = ndb.StringProperty(indexed=False) classification = ndb.IntegerProperty(indexed=False, default=0)
class Personnel(CustomBaseModel): _message_fields_schema = ('companyKey', 'name', 'lastName', 'stage', 'specialty', 'comment', 'tariff', 'tariffTimeUnit') companyKey = ndb.KeyProperty(kind=Company) name = ndb.StringProperty() lastName = ndb.StringProperty() stage = ndb.StringProperty() specialty = ndb.StringProperty() comment = ndb.StringProperty() tariff = ndb.FloatProperty() tariffTimeUnit = ndb.StringProperty() def personnel_m(self, data, companyKey): personnel = Personnel() #Crea una variable de tipo Personnel personnel.populate( data ) #Llena la variables con los datos dados por el request en main.py personnel.companyKey = companyKey #inserta el entityKey de la empresa que es un parametro que se manda en main.py personnel.put() #inserta o hace un update depende del main.py return 0
class Deliverer(ndb.Model): name = ndb.StringProperty() job = ndb.KeyProperty(kind=BeerOrder) email = ndb.StringProperty() salary = ndb.FloatProperty() dateHired = ndb.DateProperty(auto_now_add=True) @staticmethod def get_by_name(name): result = Deliverer.query(Deliverer.name == name).fetch(1) if result: return result[0] else: return None @staticmethod def get_by_email(email): result = Deliverer.query(Deliverer.email == email).fetch(1) if result: return result[0] else: return None @staticmethod def get_all_deliverers(): results = Deliverer.query().order(Deliverer.dateHired).fetch() return results def assign_job(self, order): if order.status == "Delivering": emailsender.send_assign_email(self.email, order) self.job = order.key self.put() def unassign_job(self): if self.job: #emailsender.send_unassign_email(self.email, self.job) self.job = None self.put()
class CountertopShape(ndb.Model): A = ndb.FloatProperty(indexed=False) B = ndb.FloatProperty(indexed=False) C = ndb.FloatProperty(indexed=False) D = ndb.FloatProperty(indexed=False) E = ndb.FloatProperty(indexed=False) F = ndb.FloatProperty(indexed=False) shape = msgprop.EnumProperty(Shape, required=True) sqft = ndb.ComputedProperty(lambda self: self.compute_sqft()) def compute_sqft(self): if self.shape == Shape.L: return (self.A * self.B + self.C * self.D) / 144.0 if self.shape == Shape.U: return (self.A * self.B + self.F * (self.C - self.E) + self.C * self.D) / 144.0 if self.shape == Shape.R: return (self.A * self.B) / 144.0 return 0 def get_sides(self): if self.shape == Shape.L: return (self.A, self.B, self.C, self.D) elif self.shape == Shape.R: return (self.A, self.B) elif self.shape == Shape.U: return (self.A, self.B, self.C, self.D, self.E, self.F) return () def get_name(self): if self.shape == Shape.L: return 'L-shape' elif self.shape == Shape.U: return 'U-shape' elif self.shape == Shape.R: return 'R-shape' return 'Shape: other' def get_path(self): if self.shape == Shape.L: return '/lshape' if self.shape == Shape.U: return '/ushape' if self.shape == Shape.R: return '/rshape' return '/contact'
class PaymemtWF(ndb.Model): # provider expected amount prExpAmt = ndb.FloatProperty() # platform expected amount plExpAmt = ndb.FloatProperty() # taxes expected txExpAmt = ndb.FloatProperty() # total expected ttlExpAmt = ndb.FloatProperty() additionalPendingCharges = ndb.FloatProperty(repeated=True) # coupon code and value paymentCoupon = ndb.StructuredProperty(PaymentCouponStruc) # expected currency expCurr = ndb.StringProperty(default="INR") # total paid amount totalPaidAmount = ndb.FloatProperty() # paid in currency paidCurrency = ndb.StringProperty(default="INR") paymentProviderId = ndb.StringProperty() paymentToken = ndb.StringProperty(repeated=True) paymentBeginTS = ndb.DateTimeProperty(repeated=True) paymentConfirmToken = ndb.StringProperty(repeated=True) paymentConfirmTS = ndb.DateTimeProperty(repeated=True) #1=not_initiated, #2 payment_in_process, #3 payment_processed, #4 payment_denied paymentStatusChain = ndb.IntegerProperty(repeated=True) paymentStatus = ndb.IntegerProperty(default=1) def deriveTotalExpectedAmount(self): self.ttlExpAmt = self.prExpAmt + self.plExpAmt + self.txExpAmt def applyCoupon(self, couponObj): self.paymentCoupon = couponObj adjustedTotalAmount = self.ttlExpAmt - couponObj.couponValue if(adjustedTotalAmount <= 0): adjustedTotalAmount = 0 return adjustedTotalAmount
class Proposal(ndb.Model): requestId = ndb.StringProperty() # May be null title = ndb.StringProperty() detail = ndb.StringProperty() creator = ndb.StringProperty() allowEdit = ndb.BooleanProperty() freezeUserInput = ndb.BooleanProperty(default=False) voteAggregateStartTime = ndb.IntegerProperty() numPros = ndb.IntegerProperty(default=0) numCons = ndb.IntegerProperty(default=0) netPros = ndb.IntegerProperty(default=0) # numPros - numCons score = ndb.FloatProperty(default=0) lastSumUpdateTime = ndb.IntegerProperty(default=0) words = ndb.StringProperty(repeated=True) # Experimental hideReasons = ndb.BooleanProperty(default=False) # Proposal-ids for empty (hidden) reasons emptyProId = ndb.StringProperty() emptyConId = ndb.StringProperty() def setContent(self, title, detail): self.title = title self.detail = detail # Index content words words = text.uniqueInOrder( text.removeStopWords(text.tokenize(title) + text.tokenize(detail))) words = words[0: conf.MAX_WORDS_INDEXED] # Limit number of words indexed self.words = text.tuples(words, maxSize=2) def updateScore(self): contentLen = (len(self.title) if self.title else 0) + (len( self.detail) if self.detail else 0) self.score = float(self.netPros) / float(contentLen + 100.0)
class Product(ndb.Model): """Datastore model representing product""" partial_strings = ndb.StringProperty(repeated=True) product_name = ndb.StringProperty() price = ndb.FloatProperty() url = ndb.StringProperty() type = ndb.StringProperty() def _pre_put_hook(self): """Before save, parse product name into strings""" if self.product_name: product_name_lst = regex_replace.sub( ' ', self.product_name.lower()).split(' ') product_name_lst = [ x for x in product_name_lst if x and len(x) > 2 ] self.partial_strings = product_name_lst @classmethod def search(cls, text_query): """Execute search query""" words = text_query.lower().split(' ') words = [w for w in words if w] query = cls.query() for word in words: query = query.filter(cls.partial_strings == word) return query.fetch(20) @classmethod def create(cls, item): """Create object (doesn't save)""" key = ndb.Key(cls, int(item['sku'])) obj = cls(key=key, price=float(item['price']), product_name=item['name'], url=item['url'], type=item['type']) return obj
class TailboneCEInstance(polymodel.PolyModel): load = ndb.FloatProperty(default=0) address = ndb.StringProperty() # address of the service with port number e.g. ws://72.4.2.1:2345/ zone = ndb.StringProperty() status = ndb.StringProperty(default=InstanceStatus.PENDING) pool = ndb.KeyProperty() @staticmethod def calc_load(stats): """Calculate load value 0 to 1 from the stats object.""" return stats.get("mem", 0) PARAMS = { "kind": "compute#instance", "name": "default", "zone": api_url(PROJECT_ID, "zones", DEFAULT_ZONE), "image": api_url("debian-cloud", "global", "images", "debian-7-wheezy-v20130515"), "machineType": api_url(PROJECT_ID, "zones", DEFAULT_ZONE, "machineTypes", DEFAULT_TYPE), "networkInterfaces": [ { "kind": "compute#networkInterface", "network": api_url(PROJECT_ID, "global", "networks", "default"), "accessConfigs": [ { "type": "ONE_TO_ONE_NAT", "name": "External NAT" } ], } ], "serviceAccounts": [ { "kind": "compute#serviceAccount", "email": "default", "scopes": SCOPES } ], }
class Order(Base): status = ndb.IntegerProperty(default=ORDER_STATUS['now']) products = ndb.StructuredProperty(OrderProduct, repeated=True) customer = ndb.KeyProperty(User) price = ndb.FloatProperty() def _post_put_hook(self, future): customer = self.customer.get() feedback_email = Config.get_master_db().feedback_email if customer and feedback_email: if self.status == ORDER_STATUS['now']: managers = Manager.query(Manager.is_mailable == True) for manager in managers: if manager.email: mail.send_mail( sender=feedback_email, to=manager.email, subject=u'[%s] - Новый заказ на сумму %s' % (Config.get_master_db().brand_name, self.price), body=render_template('order/emails/order.txt', order=self), html=render_template('order/emails/order.html', order=self))
class Assignment(Base): """Assignments are particular to courses and have unique names.""" name = ndb.StringProperty() # E.g., cal/cs61a/fa14/proj1 display_name = ndb.StringProperty() url = ndb.StringProperty() points = ndb.FloatProperty() templates = ndb.JsonProperty() creator = ndb.KeyProperty(User) course = ndb.KeyProperty(Course) max_group_size = ndb.IntegerProperty() due_date = ndb.DateTimeProperty() lock_date = ndb.DateTimeProperty() # no submissions after this date active = ndb.ComputedProperty( lambda a: a.due_date and datetime.datetime.now() <= a.due_date) revision = ndb.BooleanProperty(default=False) autograding_enabled = ndb.BooleanProperty(default=False) grading_script_file = ndb.TextProperty() zip_file_url = ndb.StringProperty() # TODO Add services requested @classmethod def _can(cls, user, need, obj, query): if need.action == "index": return query if user.is_admin: return True if need.action == "get": return True elif need.action in ["grade", 'delete', 'create', 'put']: if obj and isinstance(obj, Assignment): return Participant.has_role(user, obj.course, STAFF_ROLE) return False def __lt__(self, other): """ Allows us to sort assignments - reverse order so that latest due dates come first """ return self.due_date > other.due_date
class DeletedHacker(ndb.Model): name = ndb.StringProperty() school = ndb.StringProperty() year = ndb.StringProperty() email = ndb.StringProperty() shirt_gen = ndb.StringProperty() shirt_size = ndb.StringProperty() dietary_restrictions = ndb.StringProperty() resume = ndb.BlobKeyProperty() date = ndb.DateTimeProperty() links = ndb.StringProperty() teammates = ndb.StringProperty() teammates_emailed = ndb.BooleanProperty() hardware_hack = ndb.StringProperty() first_hackathon = ndb.StringProperty() phone_number = ndb.StringProperty() # normalized to only digits, plz secret = ndb.StringProperty() admit_priority = ndb.FloatProperty(default=0) admitted_email_sent_date = ndb.DateTimeProperty() post_registration_email_sent_date = ndb.DateTimeProperty() waitlist_email_sent_date = ndb.DateTimeProperty() rsvpd = ndb.BooleanProperty() rsvp_reminder_sent_date = ndb.DateTimeProperty(default=None) checked_in = ndb.BooleanProperty() ip = ndb.StringProperty() receipts = ndb.BlobKeyProperty(repeated=True) #different deletedDate = ndb.DateTimeProperty(auto_now_add=True) deletedCause = ndb.StringProperty( choices=["unregistered", "expired", "manual"])
class Order(ndb.Model): """ More complex mdoel """ item = ndb.KeyProperty(Item) is_payed = ndb.BooleanProperty() date_added = ndb.DateProperty() customer = ndb.StringProperty() memo = ndb.TextProperty() price = ndb.FloatProperty() item_struct = ndb.StructuredProperty(Item) def __unicode__(self): return "%s ordered %s" % (self.customer, self.item.get()) def __str__(self): return self.__unicode__() class Meta(): def __init__(self): self.fields = [ fields.KeyField("item", "Item", required=True, query=Item.query()), fields.DateField("date_added", "Date", required=True), fields.CheckboxField("is_payed", "Payed"), fields.TextField("customer", "Customer", required=True), fields.BigTextField("memo", "Memo"), fields.FloatField("price", "Price"), fields.TextField("item_struct.name", "Item Name", required=True), fields.BigTextField("item_struct.description", "Item Description"), fields.FileField("item_struct.image", "Item Image") ]
class LoginHistory(ndb.Model): user_id = ndb.StringProperty() host = ndb.StringProperty() user_agent = ndb.StringProperty() cookie_key = ndb.StringProperty() last_active = ndb.FloatProperty() created_date = ndb.DateTimeProperty(auto_now_add=True) @classmethod def add_login_history(cls, user_id, host, user_agent, cookie_key, parent_key): history = cls(user_id=user_id, host=host, user_agent=user_agent, cookie_key=cookie_key, last_active=time.time(), parent=parent_key) history.put() return history @classmethod def get_history(cls, self, HISTORY_PARENT_KEY): return cls.query(cls.user_id == self.session.get('user_id'), ancestor=HISTORY_PARENT_KEY).order(-cls.created_date)
class MRExemptionRecord(ndb.Model): subjects = ndb.StringProperty(repeated=True) documents = ndb.StructuredProperty(MRExemptionRecordDocument, repeated=True) publication_id = ndb.IntegerProperty() budget_code = ndb.StringProperty() prefixes = ndb.StringProperty(repeated=True) start_date = ndb.DateProperty() end_date = ndb.DateProperty() claim_date = ndb.DateProperty() last_update_date = ndb.DateProperty() contact = ndb.StringProperty() contact_email = ndb.StringProperty() regulation = ndb.StringProperty() supplier = ndb.StringProperty() supplier_id = ndb.StringProperty() url = ndb.StringProperty() publisher = ndb.StringProperty() history = ndb.StructuredProperty(MRExemptionRecordHistory, repeated=True) volume = ndb.FloatProperty() reason = ndb.StringProperty() decision = ndb.StringProperty() description = ndb.StringProperty(indexed=False) entity_id = ndb.StringProperty() entity_kind = ndb.StringProperty() last_modified = ndb.DateTimeProperty(auto_now=True)
class Product(EndpointsModel): _message_fields_schema = ('id', 'model', 'description', 'created_at', 'manufacturer', 'category', 'status', 'description', 'short_description', 'label', 'specifications', 'price', 'photo', 'features') model = ndb.StringProperty(required=True) manufacturer = ndb.StructuredProperty(Manufacturer) category = ndb.StructuredProperty(Category) status = ndb.StructuredProperty(Status) specifications = ndb.StructuredProperty(Specifications) description = ndb.StringProperty() short_description = ndb.StringProperty() label = ndb.StringProperty() price = ndb.FloatProperty() photo = ndb.StringProperty() features = ndb.StringProperty(repeated=True) created_at = ndb.DateTimeProperty(auto_now_add=True) updated_at = ndb.DateTimeProperty(auto_now_add=True) def IdSet(self, value): if not isinstance(value, basestring): raise TypeError('ID must be a string.') self.UpdateFromKey(ndb.Key(Product, value))
class UserSyndicate(ndb.Model): user_key = ndb.KeyProperty(kind=User) syndicate_key = ndb.KeyProperty(kind=Syndicate) # how much money the user has got in the kitty for this syndicate status = ndb.StringProperty(choices=['Invited', # a manager has invited user to the syndicate, but they haven't accepted 'Pending', # a user has entered a code to join a syndicate, but the manager hasn't approved 'Approved']) # a user who is a member of a syndicate kitty = ndb.FloatProperty(default=0.0) # denormalized values user_name = ndb.StringProperty() syndicate_name = ndb.StringProperty() game_name = ndb.StringProperty() def _pre_put_hook(self): ndb.Model._pre_put_hook(self) user = self.user_key.get() syndicate = self.syndicate_key.get() self.user_name = user.display_name self.syndicate_name = syndicate.name self.game_name = syndicate.game_name