def write_classroom(self, classroom): students = ndb.get_multi(classroom.students) assignments = models.Assignment.query(ancestor=classroom.key) response = models.to_dict(classroom) response['students'] = [models.to_dict(student) for student in students] response['assignments'] = [models.to_dict(assignment) for assignment in assignments] self.write(response)
def write(self, data): if isinstance(data, ndb.Model): data = models.to_dict(data) elif isinstance(data, list) and len(data) > 0 and isinstance(data[0], ndb.Model): data = [models.to_dict(m) for m in data] json_txt = ")]}',\n" + json.dumps(data, default=datetime_handler) logging.info(self.request.path + ' response: ' + json_txt) self.response.headers['Content-Type'] = 'application/json; charset=UTF-8' self.response.write(json_txt)
def to_dict(self): ret = models.to_dict(self) ret["channel_id"] = self.key().name() q = VideoModel.all() q.ancestor(self) ret["total"] = q.count() return ret
def get(self): tab = self.request.get('tab') if not tab: tab = 'all' #show all, unassigned, and every region on the page, use display none on the front end to show one list at time allchapters = models.getallchapters() unassignedchapters = self.unassignedchapters() regions = models.getallregions() regionswchapters = {} for r in regions: #get the chapter list for each region chs = models.getchaptersinregion(r) chaptersdict = [] for c in chs: chapterkey = c.key() chapterdict = models.to_dict(c) chapterdict['key'] = str(chapterkey) chaptersdict.append(chapterdict) regionswchapters[r.name] = chaptersdict template_values = { 'regions' : regions, 'chaptersbyregion' : regionswchapters, 'allchapters' : allchapters, 'unassignedchapters' : unassignedchapters, 'tabname' : tab } path = os.path.join(os.path.dirname(__file__), 'templates/chapters.html') self.response.out.write(template.render(path, template_values))
def RestaurantTag_Retrieve(): """ Returns the complete list of tags that can be used for restaurants """ items = [models.to_dict(x) for x in models.RestaurantTag.all()] response = {} response['Count'] = len(items) response['Items'] = items return {}
def get(self): selectiontype = self.request.get('selectiontype') regionkey = self.request.get('regionkey') if selectiontype == 'all': chapters = models.getallchapters() print 'all' elif selectiontype == 'unassigned': chapters = models.getallchapters() chaptersworegion = [] for chapter in chapters: if not chapter.parent(): chaptersworegion.append(chapter) chapters = chaptersworegion #print 'unassigned' elif selectiontype == 'region': chapters = models.getchaptersinregion(regionkey) #print 'region' else: chapters = [] #print 'broken' chaptersarr = [] for ch in chapters: chaptersarr.append(models.to_dict(ch)) self.response.out.write(json.dumps({'chapters': chaptersarr}))
def get(self): selectiontype = self.request.get('selectiontype') regionkey = self.request.get('regionkey') if selectiontype == 'all': chapters = models.getallchapters() print 'all' elif selectiontype == 'unassigned': chapters = models.getallchapters() chaptersworegion = [] for chapter in chapters: if not chapter.parent(): chaptersworegion.append(chapter) chapters = chaptersworegion #print 'unassigned' elif selectiontype == 'region': chapters = models.getchaptersinregion(regionkey) #print 'region' else: chapters = [] #print 'broken' chaptersarr = [] for ch in chapters: chaptersarr.append(models.to_dict(ch)) self.response.out.write( json.dumps({ 'chapters' : chaptersarr }) )
def Region_Retrieve(): """ Returns the complete region list """ items = [models.to_dict(x) for x in models.Region.all()] response = {} response['Count'] = len(items) response['Items'] = items return response
def get(self): tab = self.request.get('tab') if not tab: tab = 'all' #show all, unassigned, and every region on the page, use display none on the front end to show one list at time allchapters = models.getallchapters() unassignedchapters = self.unassignedchapters() regions = models.getallregions() regionswchapters = {} for r in regions: #get the chapter list for each region chs = models.getchaptersinregion(r) chaptersdict = [] for c in chs: chapterkey = c.key() chapterdict = models.to_dict(c) chapterdict['key'] = str(chapterkey) chaptersdict.append(chapterdict) regionswchapters[r.name] = chaptersdict template_values = { 'regions': regions, 'chaptersbyregion': regionswchapters, 'allchapters': allchapters, 'unassignedchapters': unassignedchapters, 'tabname': tab } path = os.path.join(os.path.dirname(__file__), 'templates/chapters.html') self.response.out.write(template.render(path, template_values))
def update_or_create_event(event, result): """Update or create an event in elasticsearch using the response of search_event(event) request. """ url = _HOSTNAME + _INDEX + 'event/' accompanists = models.Session.query(models.Accompanists).\ filter(models.Accompanists.event_id == event.id).all() print([(acc.event_id, acc.date) for acc in accompanists]) if result['hits']['total'] == 0: # We need to create the event data = models.to_dict(event) data['accompanists'] = add_accompanists( accompanists, data['begin'], data['end']) data['from'] = [get_unique_id()] del data['id'] UrlRequest(url=url, req_body=json.dumps(data), on_error=print_error, on_success=lambda req, res: send_contacts(event, result, _id=res['_id']), timeout=1, on_failure=print_error) else: res = result['hits']['hits'][0]['_source'] if get_unique_id() in res['from']: send_contacts(event, result) return # We already synchronize event, just send the contacts # We add our id and our accompanists res['from'].append(get_unique_id()) res['accompanists'] = add_accompanists( accompanists, res['begin'], res['end'], res['accompanists']) url += result['hits']['hits'][0]['_id'] + '/_update' res = {"doc": res} UrlRequest(url=url, req_body=json.dumps(res), on_error=print_error, on_success=lambda req, res: send_contacts(event, result), timeout=1, on_failure=print_error)
def search_event(event, return_=False): """Returns the result of a search request An event is unique by its name, location and dates. """ url = _HOSTNAME + _INDEX + 'event/_search' method = "GET" d = models.to_dict(event) del d['id'] data = {"query": {"bool": {"must": [{"match_phrase": {k: v}} for k, v in d.iteritems()] } } } success = None if return_ else \ lambda req, res: update_or_create_event(event, res) req = UrlRequest(url=url, req_body=json.dumps(data), method=method, timeout=1, on_error=print_error, on_success=success) if return_: req.wait() # We need the result before continuing return req.result
def post(self): chapterkey = self.request.get('chapterkey') chapter = models.getchapter(chapterkey) chapterdict = models.to_dict(chapter) self.response.out.write( json.dumps({ 'chapter': chapterdict, 'chapterkey': chapterkey }))
def RestaurantDetail_Retrieve(): """ Returns the restaurant details """ restaurant = None for restaurant in models.Restaurant.all().filter("Uid =", RESTAURANT_UID): break assert restaurant, 'The expected restaurant record %r does not exists? It should\'ve been created already' % RESTAURANT_UID response = {} response['Count'] = 1 response['Items'] = [models.to_dict(restaurant)] return response
def create_or_none(result, contact, date, _id): if 'hits' not in result or 'total' not in result['hits'] or \ result['hits']['total'] == 0: url = _HOSTNAME + _INDEX + 'contact/?parent=' + str(_id) data = models.to_dict(contact) data['date'] = str(date) data['tablet'] = get_unique_id() del data['id'] UrlRequest(url=url, req_body=json.dumps(data), on_success=print_success, on_error=print_error, on_failure=print_error)
def post(self): zipcodequery = self.request.get('q') chapters = models.getchaptersfromzip(zipcodequery) chaptersdict = [] for c in chapters: coords = helpers.coordsfromchapterkey(c) chapterkey = c.key() chapterdict = models.to_dict(c) chapterdict['coords'] = coords chapterdict['key'] = str(chapterkey) chaptersdict.append(chapterdict) self.response.out.write( json.dumps({ 'chapters' : chaptersdict }) )
def post(self): zipcodequery = self.request.get('q') chapters = models.getchaptersfromzip(zipcodequery) chaptersdict = [] for c in chapters: coords = helpers.coordsfromchapterkey(c) chapterkey = c.key() chapterdict = models.to_dict(c) chapterdict['coords'] = coords chapterdict['key'] = str(chapterkey) chaptersdict.append(chapterdict) self.response.out.write(json.dumps({'chapters': chaptersdict}))
def post(self): regionkey = self.request.get('regionkey') region = models.getregion(regionkey) chapters = models.getchaptersinregion(region) chaptersdict = [] for c in chapters: coords = helpers.coordsfromchapterkey(c) chapterkey = c.key() chapterdict = models.to_dict(c) chapterdict['coords'] = coords chapterdict['key'] = str(chapterkey) chaptersdict.append(chapterdict) self.response.out.write( json.dumps({ 'chapters' : chaptersdict, 'regionkey' : regionkey }) )
def get(self): regionkey = self.request.get('regionkey') region = models.getregion(regionkey) chapters = models.getchaptersinregion(region) chaptersdict = [] for c in chapters: coords = helpers.coordsfromchapterkey(c) chapterkey = c.key() chapterdict = models.to_dict(c) chapterdict['coords'] = coords chapterdict['key'] = str(chapterkey) chaptersdict.append(chapterdict) self.response.out.write( json.dumps({ 'chapters' : chaptersdict }) )
def RestaurantDetail_Update(Title=None, Details=None, Tags=None, Regions=None): """ Updates the restaurant details """ restaurant = None for restaurant in models.Restaurant.all().filter("Uid =", RESTAURANT_UID): break assert restaurant, 'The expected restaurant record %r does not exists? It should\'ve been created already' % RESTAURANT_UID if Title is not None: restaurant.Title = Title if Details is not None: restaurant.Details = Details if Tags is not None: restaurant.Tags = Tags if Regions is not None: restaurant.Regions = Regions restaurant.put() response = {} response['Count'] = 1 response['Items'] = [models.to_dict(restaurant)] return response
def post(self): if self.request.get('chapterkey'): chapters = [models.getchapter(self.request.get('chapterkey'))] elif self.request.get('regionkey'): chapters = models.getchaptersinregion(models.keyfromstr(self.request.get('regionkey'))) else: pass chaptersdict = [] for c in chapters: coords = helpers.coordsfromchapterkey(c) chapterkey = c.key() chapterdict = models.to_dict(c) chapterdict['coords'] = coords chapterdict['key'] = str(chapterkey) chaptersdict.append(chapterdict) self.response.out.write( json.dumps({ 'chapters' : chaptersdict }) )
def post(self): if self.request.get('chapterkey'): chapters = [models.getchapter(self.request.get('chapterkey'))] elif self.request.get('regionkey'): chapters = models.getchaptersinregion( models.keyfromstr(self.request.get('regionkey'))) else: pass chaptersdict = [] for c in chapters: coords = helpers.coordsfromchapterkey(c) chapterkey = c.key() chapterdict = models.to_dict(c) chapterdict['coords'] = coords chapterdict['key'] = str(chapterkey) chaptersdict.append(chapterdict) self.response.out.write(json.dumps({'chapters': chaptersdict}))
def get(self): """ Simple offset-based endless json/jsonp feed """ articles = Article.all().filter('publish_state = ', True)\ if self.request.get('start') and self.request.get('end'): articles = articles.filter('publish_date >=', datetime.strptime(self.request.get('start'), '%d/%m/%Y') ).filter('publish_date <=', datetime.strptime(self.request.get('end'), '%d/%m/%Y')) articles = articles.order('-publish_date').fetch(10, offset=int(self.request.get('offset', 0))) articles = [to_dict(item) for item in articles] callback = self.request.get('callback') if callback: self.jsonp_response(articles, callback) else: self.json_response(articles)
def _iterconvert(obj): # namedtuple/sqlalchemy result if isinstance(obj, tuple) and hasattr(obj, "_asdict"): # this doesn't include any columns without label()s dct = obj._asdict() # sqlalchemy result's asdict has broken ordering if not isinstance(dct, OrderedDict): dct = OrderedDict((k, dct[k]) for k in obj._fields) obj = dct if isinstance(obj, db.Model.query_class): return [_iterconvert(o) for o in obj] elif isinstance(obj, db.Model): return to_dict(obj) elif isinstance(obj, (list, tuple)): return [_iterconvert(o) for o in obj] elif isinstance(obj, dict): items = obj.items() if not isinstance(obj, OrderedDict): # same as sort_keys=True items = sorted(items, key=lambda kv: kv[0]) return OrderedDict([(k, _iterconvert(v)) for k, v in items]) return obj
def _iterconvert(obj): # namedtuple/sqlalchemy result if isinstance(obj, tuple) and hasattr(obj, '_asdict'): # this doesn't include any columns without label()s dct = obj._asdict() # sqlalchemy result's asdict has broken ordering if not isinstance(dct, OrderedDict): dct = OrderedDict((k, dct[k]) for k in obj._fields) obj = dct if isinstance(obj, db.Model.query_class): return [_iterconvert(o) for o in obj] elif isinstance(obj, db.Model): return to_dict(obj) elif isinstance(obj, (list, tuple)): return [_iterconvert(o) for o in obj] elif isinstance(obj, dict): items = obj.items() if not isinstance(obj, OrderedDict): # same as sort_keys=True items = sorted(items, key=lambda kv: kv[0]) return OrderedDict([(k, _iterconvert(v)) for k, v in items]) return obj
def to_dict(self): ret = models.to_dict(self) ret["video_id"] = self.key().id() ret["channel_id"] = self.parent_key().name() return ret;
def get_items(self, session, clauses=None, max_items=None): res = self.group_by(session, Generator.version, self._outerjoins, clauses=clauses, max_items=max_items) return to_dict(res)
def post(self): chapterkey = self.request.get('chapterkey') chapter = models.getchapter(chapterkey) chapterdict = models.to_dict(chapter) self.response.out.write( json.dumps({ 'chapter' : chapterdict , 'chapterkey' : chapterkey }) )
def get_items(self, session, clauses=None, max_items=None): res = self.group_by(session, Sut.buildarch, self._outerjoins, clauses=clauses, max_items=max_items) return to_dict(res)
def get_items(self, session, clauses=None, max_items=None): res = self.group_by(session, File.givenpath, self._outerjoins, clauses=clauses, max_items=max_items) return to_dict(res)
def get_items(self, session, clauses=None, max_items=None): res = self.group_by(session, Result.testid, self._outerjoins, clauses=clauses, max_items=max_items) return to_dict(res)
def get_items(self, session, clauses=None, max_items=None): res = self.group_by(session, Function.name, self._outerjoins, clauses=clauses, max_items=max_items) return to_dict(res)