class Articles (ndb.Expando): article_reference = ndb.StringProperty() topic = ndb.StringProperty() url = ndb.StringProperty() title = ndb.StringProperty() urlToImage = ndb.StringProperty() description = ndb.StringProperty() this_date = ndb.DateProperty(auto_now_add=True) def write_topic(self,topic): try: if topic != None: self.topic = topic return True else: return False except: return False def create_reference(self): import random,string try: reference = "" for i in range(256): reference += random.SystemRandom().choice(string.digits + string.ascii_lowercase) return reference except: return "" def write_reference(self,ref): try: if ref != "": self.article_reference = ref return True else: return False except: return False def write_url(self,url): try: url = str(url) if url != None: self.url = url return url except Exception as e: raise e def write_title(self,title): try: title = str(title) title = title.strip() if title != None: self.title = title return True else: return False except Exception as e: raise e def write_urlToImage(self,urlToImage): try: urlToImage = str(urlToImage) if urlToImage != None: self.urlToImage = urlToImage return True else: return False except Exception as e: raise e def write_description(self,description): try: description = str(description) description = description.strip() if description != None: self.description = description return True else: return False except Exception as e: raise e def fetch_articles(self,total): """ """ try: import random articles_url = 'https://newsapi.org/v2/everything?q=' mydate = datetime.datetime.now() this_date = str(mydate.year) + "-" + str(mydate.month) + "-" + str(mydate.day) myarticles_url = articles_url + random.choice(this_topics) + '&language=en' + '&from=' + this_date + '&apiKey=' + apiKey headers = {'Content-Type': 'text/html'} result = urlfetch.fetch(url=myarticles_url, method=urlfetch.GET, headers=headers, validate_certificate=True) try: if result.status_code == 200: myjson = json.loads(result.content) logging.info("ARE WE THERE YET") logging.info(myjson) logging.info("WE ARE THERE") return myjson else: return "{STATUS : " + str(result.status_code) + "}" except Exception as e: logging.info(e) raise e except Exception as e: logging.info(e) return {"Message": "There was an error accessing NEWS API"} def fetch_topic(self, topic): """ """ try: articles_url = 'https://newsapi.org/v2/everything?q=' mydate = datetime.datetime.now() this_date = str(mydate.year) + "-" + str(mydate.month) + "-" + str(mydate.day) myarticles_url = articles_url + topic + "&language=en" + "&from=" + this_date + "&apiKey=" + apiKey headers = {'Content-Type': 'text/html'} result = urlfetch.fetch(url=myarticles_url, method=urlfetch.GET, headers=headers, validate_certificate=True) try: if result.status_code == 200: myjson = json.loads(result.content) logging.info("ARE WE THERE YET") logging.info(myjson) logging.info("WE ARE THERE") return myjson else: return "" except Exception as e: logging.info(e.message) pass except Exception as e: logging.info(e) return "" def save_topics(self): try: for topic in this_topics: json_results = self.fetch_topic(topic=topic) if json_results != "": articles = json_results['articles'] this_date = datetime.datetime.now() this_date = this_date.date() for article in articles: self.write_url(url=article['url']) self.write_title(title=article['title']) self.write_urlToImage(urlToImage=article['urlToImage']) self.write_description(description=article['description']) self.write_reference(ref=self.create_reference()) self.put() logging.info("SAVED TOPIC : " + topic) else: pass except Exception as e: raise e
class polls(ndb.Model): picture = ndb.StringProperty() question= ndb.StringProperty() created = ndb.DateProperty(auto_now_add = True) winner= ndb.StringProperty() votelist = ndb.StringProperty()
class Gamenight(ndb.Model): """Gamenights that have been scheduled.""" invitation = ndb.KeyProperty('a', kind='Invitation') event = ndb.StringProperty('e') status = ndb.StringProperty('s', choices=['Yes', 'Probably', 'Maybe', 'No']) lastupdate = ndb.DateTimeProperty('u') # denormalized from invitation for datastore efficiency date = ndb.DateProperty('d') time = ndb.TimeProperty('t') owner = ndb.KeyProperty('o', kind='User') location = ndb.StringProperty('l', indexed=False) notes = ndb.StringProperty('n', indexed=False) def _pre_put_hook(self): creds = Auth.get() if not creds: logging.warn('No credentials found, event not updated.') return service = Utils.get_service(Auth) calendar_id = self._get_config('calendar_id') if self.status == 'Yes': if self.event: logging.info('Updating event for %s.', self.date) event = service.events().get(calendarId=calendar_id, eventId=self.event).execute() event.update(self._make_event()) service.events().update(calendarId=calendar_id, eventId=self.event, body=event).execute() else: logging.info('Creating new event for %s.', self.date) event = self._make_event() newevent = service.events().insert(calendarId=calendar_id, body=event).execute() self.event = newevent['id'] logging.info('New event: %r.', newevent) else: if self.event: logging.info('Deleting event for %s.', self.date) service.events().delete( calendarId=calendar_id, eventId=event).execute() @classmethod def _pre_delete_hook(cls, key): gn = key.get() eventid = gn.event if not eventid: return service = Utils.get_service(Auth) calendar_id = gn._get_config('calendar_id') logging.info('Deleting event: %s', eventid) service.events().delete( calendarId=calendar_id, eventId=eventid).execute() def _get_config(self, key): conf = Config.query(Config.name==key).get() if conf: return conf.value else: return None def _make_event(self): if not self.time: self.time = datetime.time(20, 0, 0) start = datetime.datetime.combine(self.date, self.time) event = { 'start': { 'dateTime': start.strftime('%Y-%m-%dT%H:%M:%S'), 'timeZone': 'America/Los_Angeles' }, 'end': { 'dateTime': self.date.strftime('%Y-%m-%dT23:59:59'), 'timeZone': 'America/Los_Angeles' }, 'description': self.notes, 'location': self.location, 'summary': 'Gamenight: %s' % self.status.upper(), } return event @classmethod def schedule(cls, date=None, status=None, fallback='Probably', priority=None): # If no date is specified, look for the next invitation that is no # later than saturday if date is None: upcoming = Invitation.query(Invitation.date >= Utils.now().date()).\ order(Invitation.date).get() if upcoming is None or upcoming.date > Utils.saturday().date(): logging.info('No future invitation found.') return None else: date = upcoming.date schedule = cls.query(cls.date==date).filter(cls.status=='Yes').get() or \ Invitation.resolve(when=date, priority=priority) or \ cls.query(cls.date==date).get() or \ Gamenight(status=fallback, date=date, lastupdate=Utils.now()) if status is not None and schedule.status != 'Yes': schedule.status = status schedule.put() logging.info('Scheduling new gamenight: %r', schedule) return schedule @classmethod def reset(cls, date=None): if date is None: date = Utils.saturday() schedule = Invitation.resolve(when=date, priority='Insist') or \ cls.query(cls.date==date).get() or \ Gamenight(status='Probably', date=date, lastupdate=Utils.now()) schedule.put() logging.info('Resetting gamenight page: %r', schedule) return schedule @classmethod def future(cls, limit): return cls.query(cls.date >= Utils.now()).order(cls.date).fetch(limit) @classmethod def this_week(cls): """Get this week's gamenight.""" g = cls.future(1) if g and g[0].is_this_week(): return g[0] else: return None def update(self): if not self.invitation: return False invite = self.invitation.get() self.time = invite.time self.location = invite.location self.notes = invite.notes self.put() return True def is_this_week(self): return self.date - Utils.now().today().date() < datetime.timedelta(7)
class Review(ndb.Model): date = ndb.DateProperty(auto_now=True) rating = ndb.IntegerProperty() visitFrequency = ndb.StringProperty() subject = ndb.StringProperty() message = ndb.TextProperty()
class GameSummary(ndb.Model): """Game Summary object""" user = ndb.KeyProperty(required=True, kind='User') trivia_game = ndb.KeyProperty(required=True, kind='TriviaGame') date = ndb.DateProperty(required=True) turns = ndb.KeyProperty(kind='Turn', repeated=True) score = ndb.IntegerProperty(required=True) @classmethod def new_game_summary(cls, user, game, date, turns): """Creates and returns a new game summary""" total_score = 0 for turn in turns: total_score += turn.get().points game_summary = GameSummary(user=user, trivia_game=game, date=date, turns=turns, score=total_score) game_summary.put() return game_summary def to_summary_form(self): (score, numCorrect, numIncorrect, clues_used) = self.aggregate_data() return GameSummaryForm(user_name=self.user.get().name, date=str(self.date), questions_answered=len(self.turns), correct=numCorrect, incorrect=numIncorrect, clues_used=clues_used, total_score=score) def to_detail_form(self): detailForms = [] for turn_key in self.turns: turn = turn_key.get() question_asked = turn.question_key.get().question answer_given = turn.given_answer clues_used = turn.clues_used if turn.is_correct: correct_msg = 'Answered Correctly' else: correct_msg = 'Answered Incorrectly' points_scored = turn.points detailForms.append(GameDetailForm(date=str(self.date), question=question_asked, answer=answer_given, clues_used=clues_used, correct=correct_msg, points=points_scored)) return detailForms def aggregate_data(self): gameTurns = ndb.get_multi(self.turns) score = 0 numCorrect = 0 numIncorrect = 0 clues_used = 0 for turn in gameTurns: score += turn.points clues_used += turn.clues_used if turn.is_correct: numCorrect += 1 else: numIncorrect += 1 return [score, numCorrect, numIncorrect, clues_used]
class User(ndb.Model): name = ndb.StringProperty() birthday = ndb.DateProperty() created_date = ndb.DateTimeProperty(required=False) created_date = datetime.datetime.now()
class ContactMessages(ndb.Expando): strMessageReference = ndb.StringProperty() strNames = ndb.StringProperty() strEmail = ndb.StringProperty() strCell = ndb.StringProperty() strSubject = ndb.StringProperty() strMessage = ndb.StringProperty() strMessageExcerpt = ndb.StringProperty() strDateSubmitted = ndb.DateProperty(auto_now_add=True) strTimeSubmitted = ndb.TimeProperty(auto_now_add=True) strResponseSent = ndb.BooleanProperty(default=False) def readDateSubmitted(self): try: strTemp = str(self.strDateSubmitted) strTemp = strTemp.strip() return strTemp except: return None def readTimeSubmitted(self): try: strTemp = str(self.strTimeSubmitted) strTemp = strTemp.strip() return strTemp except: return None def readResposeSent(self): try: return self.strResponseSent except: return False def writeResponseSent(self, strinput): try: if strinput == True: self.strResponseSent = True return True else: self.strResponseSent = False return True except: return False def readNames(self): try: strTemp = str(self.strNames) strTemp = strTemp.strip() if not (strTemp == None): return strTemp else: return None except: return None def writeNames(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if not (strinput == None): self.strNames = strinput return True else: return False except: return False def readEmail(self): try: strTemp = str(self.strEmail) strTemp = strTemp.strip() if not (strTemp == None): return strTemp else: return None except: return None def writeEmail(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if not (strinput == None): self.strEmail = strinput return True else: return False except: return False def readCell(self): try: strTemp = str(self.strCell) strTemp = strTemp.strip() if not (strTemp == None): return strTemp else: return None except: None def writeCell(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if not (strinput == None): self.strCell = strinput return True else: return False except: return False def readSubject(self): try: strTemp = str(self.strSubject) strTemp = strTemp.strip() if not (strTemp == None): return strTemp else: return None except: return None def writeSubject(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if not (strinput == None): self.strSubject = strinput return True else: return False except: return False def readMessage(self): try: strTemp = str(self.strMessage) strTemp = strTemp.strip() if not (strTemp == None): return strTemp else: return None except: return None def writeMessage(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if not (strinput == None): self.strMessage = strinput MessageLen = len(self.strMessage) if MessageLen > 16: self.strMessageExcerpt = self.strMessage[0:16] else: self.strMessageExcerpt = self.strMessage return True else: return False except: return False def sendResponse(self): try: sender_address = ( 'midey.co.za Support <{}@appspot.gserviceaccount.com>'.format( app_identity.get_application_id())) mail.send_mail(sender_address, self.strEmail, self.strSubject, self.strMessage) return True except: return False
class DayChart(ndb.Model): """ Ranking results of a day """ date = ndb.DateProperty() country = ndb.StringProperty()
class Alert(ndb.Model): """Alert -- Alert object""" content = ndb.StringProperty() date = ndb.DateProperty()
class Notification(ndb.Model): user = ndb.StringProperty() date = ndb.DateProperty(auto_now_add=True) msg = ndb.TextProperty() read = ndb.IntegerProperty()
class Event(ndb.Model): """Models a daily event.""" date = ndb.DateProperty() game = ndb.IntegerProperty()
class DateCell(ndb.Model): date = ndb.DateProperty()
class SpecialText(ndb.Model): text = ndb.StringProperty() date = ndb.DateProperty() tag = ndb.StringProperty()
class Posts(ndb.Expando): """ this is for the blog """ post_url = ndb.StringProperty() post_title = ndb.StringProperty() post_description = ndb.StringProperty() post_body = ndb.StringProperty() post_date = ndb.DateProperty() post_time = ndb.TimeProperty() post_category = ndb.StringProperty() post_seo_description = ndb.StringProperty() def write_post_url(self,post_url): try: post_url = str(post_url) post_url = post_url.strip() if post_url != None: self.post_url = post_url return True else: return False except Exception as e: raise e def write_post_title(self,post_title): try: post_title = str(post_title) post_title = post_title.strip() if post_title != None: self.post_title = post_title return True else: return False except Exception as e: raise e def write_post_description(self,post_description): try: post_description = str(post_description) post_description = post_description.strip() if post_description != None: self.post_description = post_description return True else: return False except Exception as e: raise e def write_post_body(self,post_body): try: post_body = str(post_body) post_body = post_body.strip() if post_body != None: self.post_body = post_body return True else: return False except Exception as e: raise e def write_post_date(self,post_date): try: if isinstance(post_date,datetime.date): self.post_date = post_date return True else: return False except Exception as e: raise e def write_post_time(self,post_time): try: if isinstance(post_time,datetime): self.post_time = post_time return True else: return False except Exception as e: raise e def write_post_category(self,post_category): try: post_category = str(post_category) if post_category != None: self.post_category = post_category return True else: return False except Exception as e: raise e def write_post_seo_description(self,post_seo_description): try: post_seo_description = str(post_seo_description) post_seo_description = post_seo_description.strip() if post_seo_description != None: self.post_seo_description = post_seo_description return True else: return False except Exception as e: raise e
class PSI(ndb.Model): # Daily PSI at 12:00 Singapore time psi_date = ndb.DateProperty() # date of the record psi_measurement = ndb.IntegerProperty() # PSI on that date
class ContactMessages(ndb.Expando): strMessageReference = ndb.StringProperty() strNames = ndb.StringProperty() strEmail = ndb.StringProperty() strCell = ndb.StringProperty() strSubject = ndb.StringProperty() strMessage = ndb.StringProperty() strMessageExcerpt = ndb.StringProperty() strDateSubmitted = ndb.DateProperty(auto_now_add=True) strTimeSubmitted = ndb.TimeProperty(auto_now_add=True) strResponseSent = ndb.BooleanProperty(default=False) def readDateSubmitted(self): try: strTemp = str(self.strDateSubmitted) strTemp = strTemp.strip() return strTemp except: return None def readTimeSubmitted(self): try: strTemp = str(self.strTimeSubmitted) strTemp = strTemp.strip() return strTemp except: return None def readResposeSent(self): try: return self.strResponseSent except: return False def writeResponseSent(self, strinput): try: if strinput in [True, False]: self.strResponseSent = strinput return True else: return False except: return False def readNames(self): try: strTemp = str(self.strNames) strTemp = strTemp.strip() if strTemp != None: return strTemp else: return None except: return None def writeNames(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput != None: self.strNames = strinput return True else: return False except: return False def readEmail(self): try: strTemp = str(self.strEmail) strTemp = strTemp.strip() if strTemp != None: return strTemp else: return None except: return None def writeEmail(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput != None: self.strEmail = strinput return True else: return False except: return False def readCell(self): try: strTemp = str(self.strCell) strTemp = strTemp.strip() if strTemp != None: return strTemp else: return None except: return None def writeCell(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput != None: self.strCell = strinput return True else: return False except: return False def readSubject(self): try: strTemp = str(self.strSubject) strTemp = strTemp.strip() if strTemp != None: return strTemp else: return None except: return None def writeSubject(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput != None: self.strSubject = strinput return True else: return False except: return False def readMessage(self): try: strTemp = str(self.strMessage) strTemp = strTemp.strip() if strTemp != None: return strTemp else: return None except: return None def writeMessage(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput != None: self.strMessage = strinput MessageLen = len(self.strMessage) if MessageLen > 16: self.strMessageExcerpt = self.strMessage[0:16] else: self.strMessageExcerpt = self.strMessage return True else: return False except: return False def sendResponse(self): try: sender_address = ('*****@*****.**') mail.send_mail(sender_address, self.strEmail, self.strSubject, self.strMessage) return True except: return False
class Session(ndb.Model): patient_id = ndb.StringProperty() is_billed = ndb.BooleanProperty() billing_time = ndb.DateTimeProperty(indexed=False) insurance = ndb.StringProperty() mod_code = ndb.StringProperty(indexed=False) session_number = ndb.IntegerProperty(indexed=False) date = ndb.StringProperty(indexed=False) date_object = ndb.DateProperty() timestamp = ndb.DateTimeProperty(indexed=False) name = ndb.StringProperty() dob = ndb.StringProperty(indexed=False) diag = ndb.StringProperty(indexed=False) diag_code = ndb.StringProperty(indexed=False) diag_2 = ndb.StringProperty(indexed=False) diag_2_code = ndb.StringProperty(indexed=False) modality = ndb.StringProperty(indexed=False) new_issue = ndb.StringProperty(indexed=False) no_new_issue = ndb.StringProperty(indexed=False) ASS_ABLE= ndb.StringProperty(indexed=False) ASS_CONST= ndb.StringProperty(indexed=False) ASS_COOP= ndb.StringProperty(indexed=False) ASS_EFFRT= ndb.StringProperty(indexed=False) ASS_INSIG= ndb.StringProperty(indexed=False) ASS_OR= ndb.StringProperty(indexed=False) ASS_other_txt= ndb.StringProperty(indexed=False) ASS_present= ndb.StringProperty(indexed=False) ASS_present_txt= ndb.StringProperty(indexed=False) G_1_decr= ndb.StringProperty(indexed=False) G_1_decr_txt= ndb.StringProperty(indexed=False) G_1_impr= ndb.StringProperty(indexed=False) G_1_impr_txt= ndb.StringProperty(indexed=False) G_2_decr= ndb.StringProperty(indexed=False) G_2_decr_txt= ndb.StringProperty(indexed=False) G_2_impr= ndb.StringProperty(indexed=False) G_2_impr_txt= ndb.StringProperty(indexed=False) G_3_decr= ndb.StringProperty(indexed=False) G_3_decr_txt= ndb.StringProperty(indexed=False) G_3_impr= ndb.StringProperty(indexed=False) G_3_impr_txt= ndb.StringProperty(indexed=False) G_cop_skills= ndb.StringProperty(indexed=False) G_expr= ndb.StringProperty(indexed=False) G_id_res= ndb.StringProperty(indexed=False) G_other_txt= ndb.StringProperty(indexed=False) G_sc_skills= ndb.StringProperty(indexed=False) G_verb= ndb.StringProperty(indexed=False) PLN_CONT= ndb.StringProperty(indexed=False) PLN_FREQ= ndb.StringProperty(indexed=False) PLN_NXT= ndb.StringProperty(indexed=False) PLN_PSY= ndb.StringProperty(indexed=False) PLN_other_txt= ndb.StringProperty(indexed=False) RA_none= ndb.StringProperty(indexed=False) RA_others_att= ndb.StringProperty(indexed=False) RA_others_idea= ndb.StringProperty(indexed=False) RA_others_plan= ndb.StringProperty(indexed=False) RA_prop_att= ndb.StringProperty(indexed=False) RA_prop_idea= ndb.StringProperty(indexed=False) RA_prop_plan= ndb.StringProperty(indexed=False) RA_self_att= ndb.StringProperty(indexed=False) RA_self_idea= ndb.StringProperty(indexed=False) RA_self_plan= ndb.StringProperty(indexed=False) SPA_ACTOUT= ndb.StringProperty(indexed=False) SPA_AGI= ndb.StringProperty(indexed=False) SPA_AHA= ndb.StringProperty(indexed=False) SPA_ALCHUSE= ndb.StringProperty(indexed=False) SPA_ANG= ndb.StringProperty(indexed=False) SPA_ARG= ndb.StringProperty(indexed=False) SPA_AX= ndb.StringProperty(indexed=False) SPA_DIFTRAN= ndb.StringProperty(indexed=False) SPA_DIT= ndb.StringProperty(indexed=False) SPA_DM= ndb.StringProperty(indexed=False) SPA_DRGUSE= ndb.StringProperty(indexed=False) SPA_DRT= ndb.StringProperty(indexed=False) SPA_DWF= ndb.StringProperty(indexed=False) SPA_EABOR= ndb.StringProperty(indexed=False) SPA_EW= ndb.StringProperty(indexed=False) SPA_FA= ndb.StringProperty(indexed=False) SPA_FDP= ndb.StringProperty(indexed=False) SPA_FINDIF= ndb.StringProperty(indexed=False) SPA_FRU= ndb.StringProperty(indexed=False) SPA_GF= ndb.StringProperty(indexed=False) SPA_HSC= ndb.StringProperty(indexed=False) SPA_HV= ndb.StringProperty(indexed=False) SPA_I= ndb.StringProperty(indexed=False) SPA_IMPU= ndb.StringProperty(indexed=False) SPA_INT= ndb.StringProperty(indexed=False) SPA_INTI= ndb.StringProperty(indexed=False) SPA_INTP= ndb.StringProperty(indexed=False) SPA_IRR= ndb.StringProperty(indexed=False) SPA_LE= ndb.StringProperty(indexed=False) SPA_LF= ndb.StringProperty(indexed=False) SPA_LI= ndb.StringProperty(indexed=False) SPA_LM= ndb.StringProperty(indexed=False) SPA_MARC= ndb.StringProperty(indexed=False) SPA_MEDDIF= ndb.StringProperty(indexed=False) SPA_MEDNC= ndb.StringProperty(indexed=False) SPA_ML= ndb.StringProperty(indexed=False) SPA_MOTREST= ndb.StringProperty(indexed=False) SPA_MS= ndb.StringProperty(indexed=False) SPA_MUT= ndb.StringProperty(indexed=False) SPA_OT= ndb.StringProperty(indexed=False) SPA_PACH= ndb.StringProperty(indexed=False) SPA_PAP= ndb.StringProperty(indexed=False) SPA_PER= ndb.StringProperty(indexed=False) SPA_PHY= ndb.StringProperty(indexed=False) SPA_PS= ndb.StringProperty(indexed=False) SPA_PSC= ndb.StringProperty(indexed=False) SPA_PSEC= ndb.StringProperty(indexed=False) SPA_PSL= ndb.StringProperty(indexed=False) SPA_RECREL= ndb.StringProperty(indexed=False) SPA_RRA= ndb.StringProperty(indexed=False) SPA_S= ndb.StringProperty(indexed=False) SPA_SIDI= ndb.StringProperty(indexed=False) SPA_SM= ndb.StringProperty(indexed=False) SPA_SPP= ndb.StringProperty(indexed=False) SPA_SSTR= ndb.StringProperty(indexed=False) SPA_URGSUSE= ndb.StringProperty(indexed=False) SPA_VHA= ndb.StringProperty(indexed=False) SPA_WPP= ndb.StringProperty(indexed=False) SPA_WSTR= ndb.StringProperty(indexed=False) SPA_other_txt= ndb.StringProperty(indexed=False) TI_CSB= ndb.StringProperty(indexed=False) TI_PSB= ndb.StringProperty(indexed=False) TI_PSCR= ndb.StringProperty(indexed=False) TI_conf_behav= ndb.StringProperty(indexed=False) TI_decis_balnc= ndb.StringProperty(indexed=False) TI_emot_supp= ndb.StringProperty(indexed=False) TI_encour= ndb.StringProperty(indexed=False) TI_explore= ndb.StringProperty(indexed=False) TI_other_txt= ndb.StringProperty(indexed=False) TI_play_therapy= ndb.StringProperty(indexed=False) TI_pos_reinforce= ndb.StringProperty(indexed=False) TI_prob_solv= ndb.StringProperty(indexed=False) TI_real_test= ndb.StringProperty(indexed=False) TI_refl_listen= ndb.StringProperty(indexed=False) TI_valid= ndb.StringProperty(indexed=False) notes = ndb.TextProperty(indexed=False) notes_img_id = ndb.StringProperty(indexed=False)
class Tickets(ndb.Expando): strTicketID = ndb.StringProperty() strUserID = ndb.StringProperty() strSubject = ndb.StringProperty() strBody = ndb.StringProperty() strDateCreated = ndb.DateProperty() strTimeCreated = ndb.TimeProperty() strTicketOpen = ndb.BooleanProperty(default=True) # Ticket Open or Close strTicketPreference = ndb.StringProperty( default="Normal") # Normal / Urgent strDepartment = ndb.StringProperty(default="Sales") # Programming, Hosting strTicketEscalated = ndb.BooleanProperty(default=False) strAssignedTo = ndb.StringProperty( ) # Assigned to Carries the ID of the Staff Member assigned the ticket strEscalatedToID = ndb.StringProperty( ) # Staff Member the Ticket is Escalated To def writeEscalate(self, strinput): try: if strinput in [True, False]: self.strEscalate = strinput return True else: return False except: return False def writeAssignedTo(self, strinput): try: strinput = str(strinput) if strinput != None: self.strAssignedTo = strinput return True else: return False except: return False def writeEscalatedTo(self, strinput): try: strinput = str(strinput) if strinput != None: self.strEscalatedToID = strinput return True else: return False except: return False def writeTicketID(self, strinput): try: strinput = str(strinput) if strinput != None: self.strTicketID = strinput return True else: return False except: return False def CreateTicketID(self): import random, string try: strTicketID = "" for i in range(256): strTicketID += random.SystemRandom().choice( string.digits + string.ascii_lowercase) return strTicketID except: return None def writeUserID(self, strinput): try: strinput = str(strinput) if strinput != None: self.strUserID = strinput return True else: return False except: return False def writeSubject(self, strinput): try: strinput = str(strinput) if strinput != None: self.strSubject = strinput return True else: return False except: return False def writeBody(self, strinput): try: strinput = str(strinput) if strinput != None: self.strBody = strinput return True else: return False except: return False def writeDateCreated(self, strinput): try: if isinstance(strinput, datetime.date): self.strDateCreated = strinput return True else: return False except: return False def writeTimeCreated(self, strinput): try: if isinstance(strinput, datetime.time): self.strTimeCreated = strinput return True else: return False except: return False def writeTicketOpen(self, strinput): try: if strinput in [True, False]: self.strTicketOpen = strinput return True else: return False except: return False def writeTicketPreferences(self, strinput): try: strinput = str(strinput) if strinput in ["Normal", "Urgent"]: self.strTicketPreference = strinput return True else: return False except: return False def writeDepartment(self, strinput): try: strinput = str(strinput) if strinput in [ "Sales", "Programming", "Bulk SMS", "Advertising", "Surveys", "Affiliate", "Hosting" ]: self.strDepartment = strinput return True else: return False except: return False
class Product(Base): id_1c = ndb.StringProperty(verbose_name=u'Код 1С', indexed=True) catalogue_id = ndb.StringProperty(verbose_name=u'Артикул', indexed=True) barcode = ndb.StringProperty(verbose_name=u'Штрих код', default='', indexed=True) name = ndb.StringProperty(verbose_name=u'Название', default='', indexed=True) original_name = ndb.StringProperty(verbose_name=u'Оригинальное название') strip_name = ndb.ComputedProperty( lambda self: re.sub('[/!,;."\'\-0-9]', '', self.name)) @property def clear_name(self): if self.strip_name: return ' '.join(word for word in self.strip_name.split() if len(word) > 2) return '' @property def clear_name_cp1251(self): return wurls.url_fix(self.clear_name, 'cp1251') category = ndb.StringProperty(verbose_name=u'Категория', default='', indexed=True) brand = ndb.StringProperty(verbose_name=u'Бренд/Производитель', indexed=True) country = ndb.StringProperty(verbose_name=u'Страна', default='', indexed=True) rating = ndb.IntegerProperty(verbose_name=u'Рейтинг') status = ndb.IntegerProperty(verbose_name=u'Статус') is_public = ndb.BooleanProperty(verbose_name=u'Показывать на сайте?', default=True) is_available = ndb.ComputedProperty( lambda self: True if self.is_public and (self.leftovers or self.leftovers_on_way) else False) material = ndb.StringProperty(verbose_name=u'Материал', default='', indexed=False) size = ndb.StringProperty(verbose_name=u'Размер', default='', indexed=False) weight = ndb.StringProperty(verbose_name=u'Вес', default='', indexed=False) box_material = ndb.StringProperty(verbose_name=u'Материал/тип упаковки', default='', indexed=False) box_size = ndb.StringProperty(verbose_name=u'Размер упаковки', default='', indexed=False) box_weight = ndb.StringProperty(verbose_name=u'Вес упаковки', default='', indexed=False) box_amount = ndb.StringProperty(verbose_name=u'Количество в упаковке', default='', indexed=False) @property def price_retail(self): return self.price_trade * 1.65 price_trade = ndb.FloatProperty(verbose_name=u'Цена (оптовая)') vat = ndb.IntegerProperty(verbose_name=u'НДС', default=0) leftovers = ndb.IntegerProperty(verbose_name=u'Остаток на складе') leftovers_on_way = ndb.IntegerProperty(verbose_name=u'Остаток в пути') receipt_date = ndb.DateProperty(verbose_name=u'Дата поступления') badge = ndb.StringProperty(verbose_name=u'Бэйдж', indexed=False) description = ndb.TextProperty(verbose_name=u'Описание', default='') description_html = ndb.TextProperty(verbose_name=u'Описание в HTML', default='') description_md = ndb.TextProperty(verbose_name=u'Описание в Markdown', default='') short_description = ndb.TextProperty( verbose_name=u'Краткое описание, генерируется автоматически', default='') meta_keywords = ndb.TextProperty( verbose_name=u'Список ключевых слов, генерируется автоматически', default='') equipment = ndb.TextProperty(verbose_name=u'Комплектация', default='') images_list = ndb.StructuredProperty(ProductImage, repeated=True) to_sync = ndb.BooleanProperty(default=False) _PROPERTIES = Base._PROPERTIES.union([ 'id_1c', 'catalogue_id', 'barcode', 'name', 'category', 'brand', 'country', 'rating', 'status', 'is_public', 'is_available', 'material', 'size', 'weight', 'box_material', 'box_size', 'box_weight', 'box_amount', 'price_retail', 'price_trade', 'vat', 'leftovers', 'leftovers_on_way', 'receipt_date', 'description', 'description_html', 'description_md', 'short_description', 'meta_keywords', 'equipment', 'images', 'raw_images', 'url', 'to_sync' ]) @cached_property def url(self): return url_for('product.get_product', key_id=self.key.id(), _external=True) @property def images(self): return [img.url for img in self.images_list] @property def raw_images(self): return [ url_for('file.get_b_w_name', blob_key=img.blob_key, name='%s.jpg' % img.uid, _external=True) for img in self.images_list ] @property def order_count(self): cart = session.get('cart', {}) products = cart.get('products', {}) order_product = products.get(self.key.id(), {}) return order_product.get('count', 0) def _pre_put_hook(self): if not self.original_name: self.original_name = self.name self.name = clean_name(self.name) self.category = strip_string(self.category) self.badge = strip_string(self.badge) self.barcode = strip_string(self.barcode) self.brand = strip_string(self.brand) self.country = strip_string(self.country) self.material = strip_string(self.material) self.description_md = self.description_md.strip() if self.description_md: self.description_html = mistune.markdown(self.description_md) self.description = re.sub(r'(<!--.*?-->|<[^>]*>)', '', self.description_html) else: self.description = self.description.strip() self.description_md = self.description self.description_html = mistune.markdown(self.description) if self.description: self.short_description = u' '.join(self.description.split()[:5]) else: self.short_description = '' self.meta_keywords = self.clear_name.replace(' ', ', ') def _post_put_hook(self, future): set_section(Category, CategoryProduct, self, 'category') set_section(Brand, BrandProduct, self, 'brand') set_section(Country, CountryProduct, self, 'country') @classmethod def _pre_delete_hook(cls, key): clear_section_product(CategoryProduct, key) clear_section_product(BrandProduct, key) clear_section_product(CountryProduct, key) p = key.get() if p: for img in p.images_list: img.delete_blob()
class Comments(ndb.Expando): strAuthorID = ndb.StringProperty() strThreadID = ndb.StringProperty() strCommentID = ndb.StringProperty( ) # a Sixteen Character Long ID Identifying this comment strComment = ndb.StringProperty() strCommentDate = ndb.DateProperty() strCommentTime = ndb.TimeProperty() isClientComment = ndb.BooleanProperty(default=True) def writeAuthorID(self, strinput): try: strinput = str(strinput) if strinput != None: self.strAuthorID = strinput return True else: return False except: return False def writeThreadID(self, strinput): try: strinput = str(strinput) if strinput != None: self.strThreadID = strinput return True else: return False except: return False def writeCommentID(self, strinput): try: strinput = str(strinput) if len(strinput) == 16: self.strCommentID = strinput return True else: return False except: return False def CreateCommentID(self): import random, string try: strCommentID = "" for i in range(16): strCommentID += random.SystemRandom().choice( string.digits + string.ascii_lowercase) return strCommentID except: return None def writeComment(self, strinput): try: strinput = str(strinput) if strinput != None: self.strComment = strinput return True else: return False except: return False def writeIsClientComment(self, strinput): try: if strinput in [True, False]: self.isClientComment = strinput return True else: return False except: return False def writeCommentDate(self, strinput): try: if isinstance(strinput, datetime.date): self.strCommentDate = strinput return True else: return False except: return False def writeCommentTime(self, strinput): try: if isinstance(strinput, datetime.time): self.strCommentTime = strinput return True else: return False except: return False
class Snack(ndb.Model): kind = ndb.StringProperty() rating = ndb.IntegerProperty(repeated=True) quantity = ndb.IntegerProperty() calories = ndb.IntegerProperty() expiration = ndb.DateProperty()
class Item(ndb.Model): name = ndb.StringProperty(required=True) link = ndb.StringProperty() price = ndb.FloatProperty() owner = ndb.StringProperty(required=True) added = ndb.DateProperty(auto_now_add=True, indexed=True)
class Tree(ndb.Model): date = ndb.DateProperty() tree = ndb.JsonProperty()
class KSU(ndb.Model): theory = ndb.KeyProperty(kind=Theory, required=True) created = ndb.DateTimeProperty(auto_now_add=True) last_modified = ndb.DateTimeProperty(auto_now=True) description = ndb.StringProperty(required=True) secondary_description = ndb.StringProperty() comments = ndb.TextProperty() ksu_type = ndb.StringProperty() ksu_subtype = ndb.StringProperty() kpts_value = ndb.FloatProperty() importance = ndb.IntegerProperty(default=3) tags = ndb.StringProperty() parent_id = ndb.KeyProperty( ) # Ahora me esta dando un error porque lo estoy ligando a la misma clase que estoy definiendo is_active = ndb.BooleanProperty(default=True) is_critical = ndb.BooleanProperty(default=False) is_private = ndb.BooleanProperty(default=False) is_visible = ndb.BooleanProperty(default=True) in_graveyard = ndb.BooleanProperty(default=False) is_deleted = ndb.BooleanProperty(default=False) next_event = ndb.DateProperty() pretty_next_event = ndb.StringProperty() frequency = ndb.IntegerProperty(default=1) repeats = ndb.StringProperty() # KAS1 Specific repeats_on = ndb.JsonProperty( ) #Day's of the week when it repeats if the frequency is Weekly, elese the repetition date is the same day of the month or year mission_view = ndb.StringProperty(default='Principal') best_time = ndb.TimeProperty() pretty_best_time = ndb.StringProperty() is_mini_o = ndb.BooleanProperty(default=False) is_jg = ndb.BooleanProperty(default=False) target = ndb.JsonProperty( ) # For ksus that generate kpts and indicators target min, target max, reverse target etc birthday = ndb.DateProperty() timer = ndb.JsonProperty(default={ 'hours': 0, 'minutes': 0, 'seconds': 0, 'value': '00:00:00' }) cost = ndb.JsonProperty(default={ 'money_cost': 0, 'days_cost': 0, 'hours_cost': 0 }) picture = ndb.BlobProperty() #Might be used in the future times_reviewed = ndb.IntegerProperty(default=0) next_critical_burn = ndb.IntegerProperty( ) #Define siguiente fecha como ordinal en la que si no se cumplio la accion esta quema effort_denominator = ndb.IntegerProperty(default=3) wish_type = ndb.StringProperty(default='doing') ImIn_details = ndb.JsonProperty( default={ 'positive_label': 'Delighted', 'neutral_label': 'Satisfied', 'negative_label': 'Dissapointed', 'units': 'Units' })
class facts(ndb.Model): picturelink = ndb.StringProperty() facttext = ndb.StringProperty() created = ndb.DateProperty(auto_now_add = True) upvotes = ndb.IntegerProperty(default = 0) tags= ndb.StringProperty(repeated=True)
class CatT(ndb.Model): owner = ndb.UserProperty() name = ndb.StringProperty() date_of_birth = ndb.DateProperty() description = ndb.StringProperty(indexed=False)
class Invitation(ndb.Model): """Entries of offers to host.""" date = ndb.DateProperty('d') time = ndb.TimeProperty('t') owner = ndb.KeyProperty('o', kind='User') location = ndb.StringProperty('l', indexed=False) notes = ndb.StringProperty('n', indexed=False) priority = ndb.StringProperty('p', choices=['Can', 'Want', 'Insist']) def text_date(self): date = datetime.datetime.combine(self.date, self.time) if self.date == Utils.now().date().today(): return self.time.strftime('Today, %I:%M %p') if datetime.timedelta(0) < date - Utils.now() < datetime.timedelta(6): return date.strftime('%A, %I:%M %p') return date.strftime('%b %d, %I:%M %p') datetext = ndb.ComputedProperty(text_date) text_pri = { 'Can': 'Happy to host', 'Want': 'Want to host', 'Insist': 'Would really want to host' } priority_text = ndb.ComputedProperty(lambda self: self.text_pri[self.priority]) @classmethod def get(cls, key): return ndb.Key(cls, 'root', cls, int(key)).get() @classmethod def dummy(cls): return ndb.Key(cls, 'root') @classmethod def resolve(cls, when=Utils.saturday(), history=4, priority=None): """Figure out where GN should be at the given date. By default, consider the last 4 to give preference to people who haven't been hosting.""" if type(when) != datetime.date: when = when.date() logging.info('Resolving gamenight for %s', when) invitations = cls.query(cls.date == when) logging.debug('Query: %r' % invitations) if priority is not None: priorities = (priority,) else: priorities = ('Insist', 'Want', 'Can') candidates = [] # check each level separately for pri in priorities: candidates = dict([(x.owner.id(), x) for x in invitations.filter(cls.priority == pri).fetch()]) # no matches at this priority if not candidates: logging.debug('none at priority %s' % pri) continue # no need to look at lower levels logging.debug('Candidates(%s): %r' % (pri, candidates)) break # no one wants to host :( if not candidates: logging.debug('none found.') return None # more than one option, filter out the recent hosts until we run out of # recent hosts, or have just one option left. logging.debug('Candidates: %r' % candidates.keys()) if len(candidates) > 1: if history: old_nights = Gamenight.query(Gamenight.date < Utils.now()).\ order(Gamenight.date).fetch(history) while old_nights and len(candidates) > 1: owner = old_nights.pop().owner.id() if owner in candidates: logging.debug('removing previous host %s' % owner) del candidates[owner] logging.debug('Not recent candidates: %r' % candidates.keys()) # pick one at random, return the invitation object selected = random.choice(candidates.keys()) logging.debug('Selected invitation: %s\n%r' % (selected, candidates[selected])) return candidates[selected].make_gamenight() @classmethod def summary(cls): """Get upcoming saturdays, and who has invited. Returns a dictionary of dates, with a list of (who, priority) for each. """ invitations = cls.query(cls.date >= Utils.now()).\ filter(cls.date < Utils.now() + datetime.timedelta(weeks=8)).\ order(cls.date) res = {} invlist = defaultdict(list) for invite in invitations.iter(): invlist[invite.date].append(invite.owner.get().name) for date, invites in invlist.iteritems(): res[date] = ', '.join(name for name in invites) return res @classmethod def create(cls, args): """Create or update an invitation. Any given owner can have just invite per date.""" invite = Invitation.query(Invitation.date == args['when']).\ filter(Invitation.owner == args['owner']).get() if invite: invite.location = args['where'] invite.notes = args['notes'] invite.priority = args['priority'] updated = True else: invite = Invitation(date = args['when'].date(), time = args['when'].time(), owner = args['owner'], location = args['where'], notes = args['notes'], priority = args['priority'], parent = Invitation.dummy(), ) updated = False ndb.transaction(lambda: invite.put()) return updated, invite def make_gamenight(self, overwrite=False): """Create an unsaved gamenight object from an invitation. Args: overwrite - if an existing GN is already scheduled, replace it. If false, return it unchanged. """ gamenight = Gamenight.query(Gamenight.date==self.date).get() if gamenight and not overwrite: if gamenight.status == 'Yes': return gamenight if not gamenight: gamenight = Gamenight(date=self.date) gamenight.invitation = self.key gamenight.status = 'Yes' gamenight.lastupdate = Utils.now() gamenight.time = self.time gamenight.owner = self.owner gamenight.location = self.location gamenight.notes = self.notes return gamenight
class Cat(ndb.Model): owner = ndb.KeyProperty(kind=Owner) name = ndb.StringProperty() description = ndb.StringProperty(indexed=False) date_of_birth = ndb.DateProperty() image = ndb.BlobProperty()
class Video(ndb.Model): channel_id = ndb.StringProperty() video_id = ndb.StringProperty() upload_date = ndb.DateProperty() title = ndb.StringProperty() thumbnail = ndb.StringProperty()
class Comment(ndb.Model): poll_id = ndb.StringProperty() user_id = ndb.StringProperty() comment = ndb.StringProperty() date_added = ndb.DateProperty(auto_now_add=True)