def get(self): user = users.get_current_user() if user is None: self.redirect(users.create_login_url(self.request.uri)) return bookKey = Key(self.request.get('book')) q = db.GqlQuery("SELECT * FROM Book WHERE __key__ = :1", bookKey) book = q.get() if book is None or book.userid != user.user_id(): self.redirect('/books.html') return else: sheetKey = Key(self.request.get('sheet')) q = db.GqlQuery("SELECT * FROM Sheet WHERE __key__ = :1", sheetKey) sheet = q.get() template_values = { 'book': book, 'sheet': sheet, 'mySection': 'active' } path = os.path.join(os.path.dirname(__file__), 'sheet.html') self.response.out.write(template.render(path, template_values))
def post(self): user = users.get_current_user() if user is None: self.redirect(users.create_login_url(self.request.uri)) return bookKey = Key(self.request.get('book')) q = db.GqlQuery("SELECT * FROM Book WHERE __key__ = :1", bookKey) book = q.get() if book is None or book.userid != user.user_id(): self.redirect('/books.html') return else: sheetKey = Key(self.request.get('sheet')) q = db.GqlQuery("SELECT * FROM Sheet WHERE __key__ = :1", sheetKey) sheet = q.get() if sheet.author.user_id() == user.user_id(): sheet.artist = self.request.get('artist') sheet.song = self.request.get('song') sheet.content = self.request.get('content') sheet.put() self.redirect('/sheet.html?book=' + str(book.key()) + '&sheet=' + str(sheet.key())) return else: self.redirect('/books.html') return
def query_from_form(org, event, form, projection=None, distinct=None): # start query based on admin type if org.is_global_admin: query = Query(Site, projection=projection, distinct=distinct) elif org.is_local_admin: if projection is not None or distinct is not None: raise Exception("Not currently supported for local admin") query = Query(Site).filter('event in', [ incident.key() for incident in org.incidents ]) else: raise Exception("Not an admin") # if a local admin, filter to logged in event if org.is_local_admin: query.filter('event', event.key()) # apply filters if set if form.event.data: query.filter('event', Key(form.event.data)) if form.reporting_org.data: query.filter('reported_by', Key(form.reporting_org.data)) if form.claiming_org.data: query.filter('claimed_by', Key(form.claiming_org.data)) if form.work_type.data: query.filter('work_type', form.work_type.data) if form.status.data: query.filter('status', form.status.data) # apply order if form.order.data: query.order(form.order.data) return query
def post(self, key): post = self.request.POST form_data = dict( (k, post.get(k, '')) for k in ('title', 'author', 'date', 'body')) template_dict = {'form_data': form_data, 'key': key, 'show_form': True} if 'delete_article' in post: try: NewsArticle.get(Key(key)).delete() except datastore_errors.Error: template_dict['message'] = \ 'Could not delete article with key %r.' % key else: template_dict['message'] = 'Article deleted.' template_dict['show_form'] = False else: try: date = utils.parse_date(form_data['date']) except ValueError: template_dict['message'] = \ 'Date is not in the correct format (YYYY-MM-DD).' else: if key == 'new': try: article = NewsArticle(title=form_data['title'], author=form_data['author'], date=date, body=form_data['body']) article.put() except datastore_errors.Error: template_dict['message'] = \ 'Could not create new article.' else: template_dict['message'] = 'Article created.' template_dict['show_form'] = False else: try: article = NewsArticle.get(Key(key)) except BadKeyError: template_dict['message'] = \ 'Could not find article with key %r.' % key else: article.title = form_data['title'] article.author = form_data['author'] article.date = date article.body = form_data['body'] try: article.put() except datastore_errors.Error: template_dict['message'] = \ 'Could not save changes to article.' else: template_dict['form_data'] = article template_dict['message'] = 'Changes saved.' self.render_template('edit', template_dict)
def AuthenticatedGet(self, org, event): form = OrganizationFilterForm(self.request.GET) # get relevant organizations and incidents if org.is_global_admin: query = organization.Organization.all() events = event_db.Event.all() elif org.is_local_admin: query = organization.Organization.all().filter( 'incidents', event.key()) events = [event] form.event.choices = [('', 'All')] + [(e.key(), e.name) for e in events] # apply filters if form.event.data: query.filter('incidents', Key(form.event.data)) if form.active.data is not None: query.filter('is_active', form.active.data) if form.verified.data is not None: query.filter('org_verified', form.verified.data) if form.logged_in_days.data is not None: earliest_date = ( datetime.datetime.utcnow() - datetime.timedelta(days=int(form.logged_in_days.data))) query.filter('timestamp_login >=', earliest_date) self.render( form=form, org_query=query, url="/admin-edit-organization?organization=", global_admin=org.is_global_admin, )
def get(self): condition = True page = int(self.request.get('page')) if self.request.get('page') else 0 while condition: condition = False # I want my do-while loops back! off = int(self.request.get( 'page')) * SearchHandler.PER_PAGE if self.request.get( 'page') else 0 query = search.Query( query_string=self.request.get('q'), options=search.QueryOptions( limit=SearchHandler.PER_PAGE, ids_only=True, number_found_accuracy=SearchHandler.PER_PAGE + 1, offset=off)) results = Item.search_index().search(query) arr = map(lambda x: Item.get(Key(x.doc_id)), results.results) for result in arr: if result.creation_time < Item.search_expiry_cutoff(): condition = True Item.search_index().delete(str(result.key())) self.render_template( 'items/search.html', q=self.request.get('q'), results=arr, more_pages=((results.number_found - off) > SearchHandler.PER_PAGE), fewer_pages=(page != 0), per_page=SearchHandler.PER_PAGE, page=page)
def event_key_coerce(x): if type(x) is event_db.Event: return x.key() elif type(x) is Key: return x else: return Key(x)
def get(self, room_slug, message_key): room = Room.get_by_key_name(room_slug) if not room: self.error(404) self.response.out.write("no such room") return message = Message.all().filter('__key__ =', Key(message_key), 'room =', room).get() if not message: self.error(404) self.response.out.write("no such message") return message = transform_message(message) url = "/api/" sender_url = url + "account/" + str(message.sender.key()) room_url = url + "room/" + str(message.room.key().name()) payload = { 'timestamp': message.timestamp.isoformat(), 'content': message.content, 'sender': sender_url, 'room': room_url, 'event': Message_event_names[message.event], 'extra': extra, 'id': message.key().id() } json = simplejson.dumps(payload) self.response.out.write(json)
def ndfi_value_for_cells(cell_key): cell = Cell.get(Key(cell_key)) ndfi = NDFI('MOD09GA', cell.report.comparation_range(), cell.report.range()) bounds = cell.bounds(amazon_bounds) logging.info(bounds) ne = bounds[0] sw = bounds[1] polygons = [[(sw[1], sw[0]), (sw[1], ne[0]), (ne[1], ne[0]), (ne[1], sw[0])]] data = ndfi.ndfi_change_value(cell.report.base_map(), [polygons]) logging.info(data) if 'data' not in data: logging.error("can't get ndfi change value") return ndfi = data['data']['properties']['ndfiSum']['values'] for row in xrange(10): for col in xrange(10): idx = row * 10 + col count = float(ndfi['count'][idx]) s = float(ndfi['sum'][idx]) if count > 0.0: ratio = s / count else: ratio = 0.0 ratio = ratio / 10.0 #10 value is experimental # asign to cell logging.info('cell ndfi (%d, %d): %f' % (row, col, ratio)) c = cell.child(row, col) c.ndfi_change_value = ratio c.put()
def AddAssignmentUsers(assignment, selectedUsers, serverhost, requestUri): settings = GetSettings() domain = GetAppsDomain() invitees = [] failedInvitees = [] failedemails = [] for su in selectedUsers: up = None if su['type'] == 'appuser': up = GetUserProfileFromUserId(Key(su['key'])) else: up = GetUserProfileFromEmail(su['key']) if up is None: up = UserProfile() up.fname = su['fname'] up.lname = su['lname'] up.email = su['key'] up.accesslevel = "0" if settings.defaultavatar: up.userimage = settings.defaultavatar up.put() #create registration try: #logging.info ('adding reg for ' + up.email) regid = CreateNewRegistration(up.key(), assignment.courseid, assignment.key()) invitees.append(up.email) except ScormCloudError, instance: logging.error("SC Error creating Registation: " + instance.msg) failedInvitees.append(up.email) except Exception, e: logging.error("Error creating Registation: " + str(e.args)) failedInvitees.append(up.email)
def ndfi_change(self, report_id, id): r = Report.get(Key(report_id)) z, x, y = Cell.cell_id(id) cell = Cell.get_or_default(r, x, y, z) ee = ndfi = NDFI('MOD09GA', r.comparation_range(), r.range()) bounds = cell.bounds(amazon_bounds) ne = bounds[0] sw = bounds[1] # spcify lon, lat F**K, MONKEY BALLS polygons = [[(sw[1], sw[0]), (sw[1], ne[0]), (ne[1], ne[0]), (ne[1], sw[0])]] cols = 1 rows = 1 if z < 2: cols = rows = 10 data = ndfi.ndfi_change_value(r.base_map(), [polygons], rows, cols) logging.info(data) ndfi = data['data'] #data['data']['properties']['ndfiSum']['values'] if request.args.get('_debug', False): ndfi['debug'] = { 'request': ee.ee.last_request, 'response': ee.ee.last_response } return Response(json.dumps(ndfi), mimetype='application/json')
def landsat(self, report_id, id): r = Report.get(Key(report_id)) z, x, y = Cell.cell_id(id) cell = Cell.get_or_default(r, x, y, z) bounds = cell.bounds(amazon_bounds) bounds = "%f,%f,%f,%f" % (bounds[1][1], bounds[1][0], bounds[0][1], bounds[0][0]) ee = EELandsat(LANDSAT7) d = ee.list(bounds=bounds) data = {} if len(d) >= 1: x = d[-1] img_info = x.split('/')[2][3:] path = img_info[:3] row = img_info[3:6] year = int(img_info[6:10]) julian_date = img_info[10:13] date = date_from_julian(int(julian_date), year) data = { 'info': img_info, 'path': path, 'row': row, 'year': year, 'timestamp': timestamp(date), 'date': date.isoformat() } return Response(json.dumps(data), mimetype='application/json')
def get(self): r = BookmarkRemove() if not self.request.get('id'): return fb_key = self.request.get('id') user = users.get_current_user() gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id()) #get bookmark bookmark = GqlQuery( 'SELECT * FROM Bookmark WHERE ANCESTOR IS :1 AND flowerbed=:2', gamer_key, Key(fb_key)).get() if not bookmark: return bookmark.delete() r.timestamp = int(time.time()) r.id = fb_key if self.request.get('debug', False): self.response.out.write(r) else: self.response.out.write(r.SerializeToString())
def list(self, report_id): r = Report.get(Key(report_id)) cell = Cell.get_or_default(r, 0, 0, 0) return self._as_json([ x.as_dict() for x in iter(cell.children()) if not self.is_in_backlist(x) ])
def children(self, report_id, id): r = Report.get(Key(report_id)) z, x, y = Cell.cell_id(id) cell = Cell.get_or_default(r, x, y, z) cells = cell.children() return self._as_json( [x.as_dict() for x in cells if not self.is_in_backlist(x)])
def delete(self, report_id, cell_pos, id): a = Area.get(Key(id)) if a: a.delete() a = Response("deleted", mimetype='text/plain') a.status_code = 204 return a abort(404)
def list(self, report_id, cell_pos): r = Report.get(Key(report_id)) z, x, y = Cell.cell_id(cell_pos) cell = Cell.get_cell(r, x, y, z) if not cell: return self._as_json([]) else: return self._as_json([x.as_dict() for x in cell.area_set])
def list(self, report_id, cell_pos): r = Report.get(Key(report_id)) z, x, y = Cell.cell_id(cell_pos) cell = Cell.get_cell(r, x, y, z) notes = [] if cell: return self._as_json([x.as_dict() for x in cell.note_set]) return self._as_json([])
def update(self, report_id, cell_pos, id): data = json.loads(request.data) a = Area.get(Key(id)) a.geo = json.dumps(data['paths']) a.type = data['type'] a.added_by = users.get_current_user() a.save() return Response(a.as_json(), mimetype='application/json')
def create(self, report_id, cell_pos): r = Report.get(Key(report_id)) z, x, y = Cell.cell_id(cell_pos) cell = Cell.get_or_create(r, x, y, z) data = json.loads(request.data) if 'msg' not in data: abort(400) a = Note(msg=data['msg'], added_by=users.get_current_user(), cell=cell) a.save() return Response(a.as_json(), mimetype='application/json')
def rgb_mapid(self, report_id, id, r, g, b): report = Report.get(Key(report_id)) z, x, y = Cell.cell_id(id) cell = Cell.get_or_default(report, x, y, z) ndfi = NDFI('MOD09GA', report.comparation_range(), report.range()) poly = cell.bbox_polygon(amazon_bounds) mapid = ndfi.rgb_strech(poly, tuple(map(int, (r, g, b)))) if 'data' not in mapid: abort(404) return Response(json.dumps(mapid['data']), mimetype='application/json')
def get(self, report_id, id): r = Report.get(Key(report_id)) s = self.stats_for(str(r.key().id()), r.assetid, int(id)) if request.args.get('_debug', False): s['debug'] = { 'request': self.ee.ee.last_request, 'response': self.ee.ee.last_response } data = json.dumps(s) return Response(data, mimetype='application/json')
def post(self): password = self.request.POST.get("password") hashed = getHash(password) key = self.session.get('key') key_obj = Key(key) user = db.get(key_obj) user.password = hashed user.put() self.redirect("/list")
def get(self, account_key): account = Account.all().filter('__key__ =', Key(account_key)).get() if not account: # account doesn't exist self.error(404) self.response.out.write("no such account") else: self.response.out.write( template.render('templates/account.html', {'account': account}))
def list(self, report_id): cache_key = self._cache_key(report_id) data = memcache.get(cache_key) if not data: r = Report.get(Key(report_id)) ndfi = NDFI(r.comparation_range(), r.range()) data = ndfi.mapid2(r.base_map()) if not data: abort(404) memcache.add(key=cache_key, value=data, time=3600) return jsonify(data)
def post(self): if not self.current_user.admin: return self.abort(403) rating = ItemRating.get(Key(self.request.get('rating'))) if rating is not None: item = rating.item memcache.set(rating.deletion_memcache_key(), str(rating.key()), time=5) rating.unapply() rating.delete() self.log("rating deleted") self.redirect(item.url())
def update_total_stats_for_report(report_id): r = Report.get(Key(report_id)) stats = StatsStore.get_for_report(report_id) if stats: s = stats.table_accum(tables_map['Legal Amazon']) logging.info("stats for %s" % s) if s: r.degradation = s['deg'] r.deforestation = s['def'] r.put() else: logging.error("can't find stats for %s" % report_id)
def update(self, id): data = json.loads(request.data) u = User.get(Key(id)) if 'current_cells' in data: u.current_cells = data['current_cells'] if 'is_admin' in data: if data['is_admin']: u.role = "admin" else: u.role = "editor" u.put() return Response(u.as_json(), mimetype='application/json')
def get(self): next = None PAGESIZE = 30 util.insertUsersideCookies(self) self.session = True user = UserInfo() user.whoIs(self) bookmark = self.request.get("bookmark") if bookmark: bookmark = Key(self.request.get("bookmark")) else: if user.user: bookmark = Key.from_path('MySketchesSketch','-%023d' % (int(user.user_id)) + SKETCH_ZEROS) else: bookmark = Key.from_path('MySketchesSketch','-%023d' % (0) + SKETCH_ZEROS) if user.user: endKey = Key.from_path('MySketchesSketch','-%023d' % (int(user.user_id) + 1) + SKETCH_ZEROS) else: endKey = Key.from_path('MySketchesSketch','-%023d' % (1) + SKETCH_ZEROS) logging.info('starting key ' + str(bookmark)) logging.info('starting key name' + bookmark.name()) q = db.GqlQuery("SELECT * FROM MySketchesSketch WHERE __key__ >= :1 AND __key__ < :2",bookmark,endKey) sketches = q.fetch(PAGESIZE+1) if len(sketches) == PAGESIZE + 1: next = str(sketches[-1].key()) sketches = sketches[:PAGESIZE] logging.info('next key ' + next) logging.info('next key name ' + sketches[-1].key().name()) if next is None: next = "" for sketch in sketches: sketch.stringtags = util.shorten(" ".join(sketch.tags),18) template_values = { 'sketches':sketches, 'bookmark':bookmark, 'next':next, 'action':"mySketches", 'headerTitle':"My sketches", } self.generate('galleryTemplate.html',template_values)
def create(self, report_id, cell_pos): r = Report.get(Key(report_id)) z, x, y = Cell.cell_id(cell_pos) cell = Cell.get_or_create(r, x, y, z) data = json.loads(request.data) a = Area(geo=json.dumps(data['paths']), type=data['type'], added_by=users.get_current_user(), cell=cell) a.save() cell.last_change_by = users.get_current_user() cell.put() return Response(a.as_json(), mimetype='application/json')