def editposproduct(posproduct_id): form = request.json pos = Key("PosProduct", posproduct_id, parent=TypeGroup.product_ancestor()).get() if pos is None: return abort(404) if request.method == "POST": try: if "product" in form: pos.product = Key("Product", form['product'], parent=TypeGroup.product_ancestor()) prd = pos.product.get() if prd is None: raise BadValueError("Product does not exist.") pos.name = prd.contenttype elif 'name' in form: if len(form['name']) < 1: raise BadValueError("Name too short!") pos.name = form['name'] pos.product = None pos.price = form.get('price', pos.price) pos.scan_id = form.get('scan_id', pos.scan_id) pos.keycode = form.get('keycode', pos.keycode) pos.put() except BadValueError as e: return jsonify({"messages": [e.message]}, 400) return jsonify(pos) return render_template('tantalus_posproduct.html', pos=pos)
def edituser(user_id): form = request.json or request.form user = Key("User", user_id, parent=TypeGroup.relation_ancestor()).get() if request.method == "POST": user.username = form.get('username', user.username) if 'password' in form: update_password(user, form['password']) if 'relation' in form: rel = Key("Relation", int(form['relation']), ancestor=TypeGroup.relation_ancestor()) if rel.get() is None: abort(400) user.relation = rel user.right_admin = form.get('is_admin', user.right_admin) user.right_viewstock = form.get('viewstock', user.right_viewstock) user.right_viewalltransactions = form.get('viewtransactions', user.right_viewalltransactions) user.right_posaction = form.get('posaction', user.right_posaction) user.put() return jsonify(user) return render_template('tantalus_user.html', user=user, relations=Relation.query().fetch())
def cancel_game(self, request): """ JWT required. This will cancel the game associated with the provided game key. """ game_key = request.game_key payload = token.decode_jwt(request.jwt_token) try: user = Key(urlsafe=payload.get('user_key')).get() game = Key(urlsafe=game_key).get() except TypeError: raise endpoints.BadRequestException( 'key was unable to be retrieved') except ProtocolBufferDecodeError: raise endpoints.BadRequestException( 'key was unable to be retrieved') except Exception as e: raise endpoints.InternalServerErrorException( 'An error occurred when attempting to take the turn') if user is None or game is None: raise endpoints.BadRequestException( 'Could not locate the user and game specified') try: if game.player_one != user.key and game.player_two != user.key: # this isn't even the user's game! raise endpoints.UnauthorizedException( 'Can not cancel someone else\'s game') if game.player_one_completed is True and game.player_two_completed is True: raise endpoints.BadRequestException( 'Can not cancel a game that has already been completed') if game.player_one_cancelled is True or game.player_two_cancelled is True: raise endpoints.BadRequestException( 'Game has been cancelled already') # game has not been completed / cancelled already if game.player_one == user.key: game.player_one_cancelled = True game.player_two_completed = True player_two = game.player_two.get() player_two.wins += 1 game.put() player_two.put() elif game.player_two == user.key: game.player_two_cancelled = True game.player_one_completed = True player_one = game.player_one.get() player_one.wins += 1 game.put() player_one.put() return message_types.VoidMessage() except Exception as e: # print e.message raise endpoints.InternalServerErrorException( 'An error occurred while trying to cancel the game')
def post(self, user): # grab the form form = LikeForm(self.request.params) username = user # grab the user (for their key) user = User.query(User.username == username).get() if user is None: self.redirect('/user/login') return # grab the post via what should be it's key try: post = Key(urlsafe=form.key.data).get() except Exception as e: post = None if post is None: self.redirect('/') return if user.username == post.author: error = 'you can\'t like or unlike you own post' self.render("index.html", error=error) return # is the post liked by this user already? try: liked = Like.query(Like.owner == user.key, Like.post == Key(urlsafe=form.key.data)).get() except Exception as e: print e.message liked = None # let's set the Like entity up and like the post try: if liked is None: # hasn't been liked yet liked = Like(owner=user.key, post=Key(urlsafe=form.key.data), liked=True) liked.put() else: liked.liked = True if liked.liked is False else False liked.put() # inc/dec the post likes if liked.liked is True: post.likes += 1 else: post.likes -= 1 post.put() # go back to the post! self.redirect('/post/view?key=%s' % post.key.urlsafe()) return except Exception as e: # go back to the post even if we fail to like it self.redirect('/post/view?key=%s' % post.key.urlsafe()) return
def retrieve_game(self, request): """ JWT required. Retrieves the game matching the provided key, and returns the game details """ game_key = request.game_key payload = token.decode_jwt(request.jwt_token) try: user = Key(urlsafe=payload.get('user_key')) game = Key(urlsafe=game_key).get() except TypeError: raise endpoints.BadRequestException( 'key was unable to be retrieved') except ProtocolBufferDecodeError: raise endpoints.BadRequestException( 'key was unable to be retrieved') except Exception as e: raise endpoints.InternalServerErrorException( 'An error occrurred while retrieving game details') if game is None: raise endpoints.BadRequestException('That game does not exist') # k the game exists let's make sure it's the user's game if game.player_one != user and game.player_two != user: raise endpoints.UnauthorizedException( 'You are not authorized to view other players games') return ViewGameResponseForm(game_key=game_key, game=game.to_form())
def showgroup(group, page): if page < 0: page = 0 pagination = Paginator( Product.query(Product.hidden == False and Product.group == Key('Group', group, parent=TypeGroup.product_ancestor())).order( Product.contenttype), page, 20, group=group) return render_template('tantalus_products.html', group=Key('Group', group, parent=TypeGroup.product_ancestor()).get().name, showgroup=False, pagination=pagination)
def showrelation(relation_id, page): if page < 0: page = 0 pagination = Paginator( Transaction.query( Transaction.relation == Key('Relation', relation_id, parent=TypeGroup.relation_ancestor())).order( -Transaction.reference), page, 20, relation_id=relation_id) return render_template('tantalus_transactions.html', relation=Key('Relation', relation_id, parent=TypeGroup.relation_ancestor()).get(), pagination=pagination)
def post(self): """ Find the best matching song id in response to POST requests containing a file-like object with valid WAV encoding in the request body by correlating hashes and relative offsets from the WAV data with previously-computed hash records. """ request_file = self.request.body_file.file rate, src_audio = wavfile.read(request_file) votes = defaultdict(lambda: 0) hashes = list(resound.hashes(src_audio, rate)) keys = [Key(Hashes, h_id) for h_id, _ in hashes] futures = ndb.get_multi_async(keys) for (h_id, offset), future in zip(hashes, futures): entity = future.get_result() # wait for response from each key if not entity: continue for song_id, abs_offset in entity.song_list: delta = abs_offset - offset votes[(song_id, delta)] += 1 # Find the best match max_votes, best_id = 0, None p_votes, prev = 0, None s_votes, prev_2 = 0, None for (song_id, _), vote_count in votes.iteritems(): if max_votes < vote_count: max_votes, p_votes, s_votes = vote_count, max_votes, p_votes best_id, prev, prev_2 = song_id, best_id, prev elif p_votes < vote_count: p_votes, s_votes = vote_count, p_votes prev, prev_2 = song_id, prev elif s_votes < vote_count: s_votes = vote_count prev_2 = song_id msg = "Best ids:\n1. {} - {}\n2. {} - {}\n3. {} - {}" logging.debug( msg.format(best_id, max_votes, prev, p_votes, prev_2, s_votes)) if max_votes > MIN_MATCH_THRESHOLD: key = Key(Songs, best_id) song = key.get() self.response.write( json.dumps({ 'artist': song.artist, 'title': song.title, 'year': song.year }))
def post(self): user = self.validate_user() if user is not None: self.redirect('/') return form = RegisterForm(self.request.params) # validate form if not form.validate(): self.r(form) return # validate csrf if not self.validate_csrf(form.csrf_token.data): form.csrf_token.data = self.generate_csrf() self.r(form, flashes=flash('Please submit the form again')) return # check for an existing account # using the lowercase username as a key # to ensure users are unique username = form.username.data username = re.sub( r'[\!\@\#\$\%\^\&\*\-_=\+\?<>,\.\"\':;\{\}\[\]|\\~\/`]', '', username) try: user = Key("User", lower(username)).get() except: user = None if user is not None: self.r(form, flashes=flash('That username is taken')) return # create the user try: user = User( username=username, password=pw.gen_hash(form.password.data), ) user.key = Key("User", lower(user.username)) user.put() # create a hash with our secret so we know the cookie is legit later self.generate_sig(user.username) self.redirect('/?welcome=%s' % user.username) return except: # guess something happened eh? self.r(form, flashes=flash()) return
def editproduct(product_id): form = request.json product = Key("Product", product_id, parent=TypeGroup.product_ancestor()).get() if product is None: return abort(404) if request.method == "POST": if 'group' in form: group = Group.query(Group.name == form.get('group')).fetch(1) if len(group) == 0: if form.get('group', '') != '': group = Group(name=form['group']) group.put() else: return abort(400) else: group = group[0] else: group = product.group.get() try: losemods = product.losemods if 'losemods' in form: losemods = [Key("Mod", id, parent=TypeGroup.product_ancestor()) for id in form.get('losemods')] for mod in losemods: if mod.get() is None: raise BadValueError("Mod {} does not exists.".format(mod)) gainmods = product.gainmods if 'gainmods' in form: gainmods = [Key("Mod", id, parent=TypeGroup.product_ancestor()) for id in form.get('gainmods')] for mod in gainmods: if mod.get() is None: raise BadValueError("Mod {} does not exists.".format(mod)) product.contenttype = form.get('name', form.get('contenttype', product.contenttype)) product.tag = form.get('tag', '') product.group = group.key product.amount = form.get('amount', product.amount) product.value = form.get('value', product.value) product.losemods = losemods product.gainmods = gainmods product.put() except BadValueError as e: return jsonify({"messages": [e.message]}, 400) return jsonify(product) return render_template('tantalus_product.html', product=product, mods=Mod.query().fetch())
def edit_item(self): try: item = int(self.request.get("item")) month_key = self.request.get("key") month = Key(urlsafe=month_key).get() # date raw_date = self.request.get("date") date = datetime.strptime(raw_date, "%Y-%m-%d") # buyer buyer = Key(urlsafe=self.request.get("buyer")) if buyer not in month.people: raise ValueError # what what = self.request.get("what") if len(what) == 0: raise ValueError # price price = self.request.get("price") try: price = eval(price) if price <= 0: raise ValueError except Exception: self.response.status = 409 self.write("Invalid price field") # write changes to item & sort month.items month.items[item].date = date month.items[item].buyer = buyer month.items[item].what = what month.items[item].price = price month.items.sort(key=lambda x: x.date, reverse=True) # save & response month.put() ndb.sleep(0.1) month.update() self.write(month_key) except Exception as e: print(e) self.response.status = 409 self.write("One of item field is invalid.")
def get_month_info(self): try: month_key = self.request.get("key") month = Key(urlsafe=month_key).get() prev_month = month.prev_month.get().to_string_short( ) if month.prev_month else "N/A" next_month = month.next_month.get().to_string_short( ) if month.next_month else "N/A" people_in_month = ", ".join( [person.get().name for person in month.people]) # write s = ";".join( map(unicode, [ month.to_string_short(), month_key, month.time_begin_format(), month.time_end_format(), prev_month, next_month, people_in_month, month.spend, month.average, month.key.urlsafe(), ])) self.write(s) except Exception as e: print(e) self.response.status = 409 self.write( "Can not resolve this month's key. Please reload this page or try again later" )
def retrieve_invite(self, request): """ JWT required. Retrieve the next 10 invites associated with the user starting from the provided offset, or 0 """ offset = request.offset payload = token.decode_jwt(request.jwt_token) try: user = Key(urlsafe=payload.get('user_key')) except TypeError: raise endpoints.BadRequestException('key was unable to be retrieved') except ProtocolBufferDecodeError: raise endpoints.BadRequestException('key was unable to be retrieved') except Exception as e: raise endpoints.InternalServerErrorException('An error occurred when attempting to take the turn') # user is here let's get their invites invites = Invite.query(Invite.to_player == user, Invite.rejected == False, Invite.accepted == False).fetch(limit=10, offset=offset) return RetrieveInviteResponseForm( invites=[InviteForm( inviter=invite.from_player.urlsafe(), inviter_name=invite.from_player_name ) for invite in invites] )
def edittransaction(transaction_id): form = request.json transaction = Key("Transaction", transaction_id, parent=TypeGroup.transaction_ancestor()).get() if transaction is None: return abort(404) if request.method == "POST": try: old_total = transaction.total transaction = edit_transaction(transaction, form) add_to_budget(transaction.relation, old_total - transaction.total) taskqueue.add(url='/invoice', target='worker', params={'transaction': transaction.key.id()}) except BadValueError as e: return jsonify({"messages": [e.message]}, 400) return jsonify(transaction) return render_template('tantalus_transaction.html', transaction=transaction, products=Product.query(Product.hidden == False).fetch(), mods=Mod.query().fetch(), relations=Relation.query().fetch())
def addtransaction(): form = request.json ref = None if request.method == "POST": try: relation_key = Key("Relation", int(form['relation']), parent=TypeGroup.relation_ancestor()) relation = relation_key.get() if relation is None: raise BadValueError("Relation does not exist!") transaction = new_transaction(form) add_to_budget(relation_key, -transaction.total) taskqueue.add(url='/invoice', target='worker', params={'transaction': transaction.key.id()}) except BadValueError as e: if ref is not None: # free number of transaction ref.key.delete() return jsonify({"messages": [e.message]}, 400) return jsonify(transaction) return render_template('tantalus_transaction.html', products=Product.query(Product.hidden == False).fetch(), mods=Mod.query().fetch(), relations=Relation.query().fetch())
def showtransaction(transaction_id): transaction = Key("Transaction", transaction_id, parent=TypeGroup.transaction_ancestor()).get() if transaction is None: return abort(404) return render_template('tantalus_transaction_viewer.html', **transaction_record(transaction))
def get(self): results_template = JINJA_ENVIRONMENT.get_template('templates/profile.html') all_posts = Post.query().fetch() user_key = Key('User', self.session.get('user_key_id')) user_posts = Post.query(Post.author_key == user_key).order(-Post.date_time).fetch() all_comments = Comment.query().order(Comment.date_time).fetch() for post in all_posts: author = post.author_key.get() post.author_name = author.first_name + ' ' + author.last_name post.author_pic = author.dp_url author.put() for comment in all_comments: author = comment.author_key.get() comment.author_name = author.first_name + ' ' + author.last_name author.put() info = { 'first_name' : self.session.get('f_name'), 'last_name' : self.session.get('l_name'), 'email' : self.session.get('email'), 'dp_url' : self.session.get('dp_url'), 'user_posts' : user_posts, 'all_comments' : all_comments } self.response.write(results_template.render(info))
def get(self, user): # grab the comment key k = self.request.get('key', None) if k is None: self.redirect('/') return # grab the comment try: comment = Key(urlsafe=k).get() except: comment = None if comment is None: self.redirect('/') return if comment.author != user: self.redirect('/') return post = comment.key.parent().get() form = CommentForm( data={ 'csrf_token': self.generate_csrf(), 'key': comment.key.urlsafe(), 'comment': comment.content }) self.r(form, post)
def post(self): """ Add song records in response to POST requests containing JSON encoded data in the request body. Body data must be a list of dicts: [{'title': <string>, 'artist': <string>, 'year': <string>}, ...] """ entity = Key(urlsafe=API_ENTITY_KEY).get() if self.request.headers['API_KEY'] != entity.api_key: self.error(401) return logging.info("POST - message body:\n {}".format(self.request.body)) keys = [] data = json.loads(self.request.body) for song in data: song_ent = Songs.query(Songs.title == song['title'], Songs.artist == song['artist'], Songs.year == song['year']).get() if not song_ent: new_key = Songs(**song).put() keys.append(new_key.id()) else: keys.append(song_ent.key.id()) self.response.headers.add_header('Content-Type', 'application/json') self.response.out.write(json.dumps(keys))
def addposproduct(): form = request.json if request.method == "POST": try: pos = PosProduct(price=form["price"], scan_id=form.get("scan_id", ""), keycode=form.get("keycode", "")) if 'product' in form: prd = Key("Product", form['product'], parent=TypeGroup.product_ancestor()).get() if prd is None: raise BadValueError("Product does not exist.") pos.product = prd.key pos.name = prd.contenttype elif 'name' in form: if len(form['name']) < 1: raise BadValueError("Name too short!") pos.name = form['name'] else: raise BadValueError("Need to specify either product or name!") pos.put() except (BadValueError, KeyError) as e: return jsonify({"messages": [e.message]}, 400) return jsonify(pos) return render_template( 'tantalus_posproduct.html', products=Product.query(Product.hidden == False).order( Product.contenttype).fetch())
def update(self, request): startedEvent = Key(urlsafe=request.id).get() startedEvent.startTime = parseMsgTime(request.startTime) startedEvent.eventValue = request.eventValue startedEvent.activityCode = request.activityCode startedEvent.put() return (request)
def list_items(self): try: month = Key(urlsafe=self.request.get("key")).get() people = ndb.get_multi(month.people) key_to_people = {person.key: person for person in people} items = [] for item in month.items: items.append( quote("|".join([ quote(item.date.strftime("%d/%m/%y")), quote(key_to_people[item.buyer].name.encode("utf8")), quote(escape_html_tags(item.what.encode("utf8"))), quote(str(item.price)) ]))) # write self.write(";".join(items)) except Exception as e: print(e) self.response.status = 409 self.write( "Can not list items in this month. Please reload this page or try again later" )
def ExpandLinkedDict(aSourceDict): aTarget = {} aTarget["key"] = aSourceDict["key"] llinkkeyid = aSourceDict["key"] aLinksList.append(llinkkeyid) llinkobj = None if llinkkeyid: llinkkey = Key(GDSDocument, llinkkeyid) llinkobj = llinkkey.get() if llinkobj: # we have a linked object. Populate aTarget with values from the linked object. llinkdict = llinkobj.to_dict() # do transform if ther is one ltransform = GDSDocument.GetbOTLTransform(lkey) if ltransform: llinkdict = bOTL.Transform(llinkdict, ltransform) if "key" in llinkdict: del llinkdict["key"] aTarget.update(llinkdict) else: aTarget["link_missing"] = True return aTarget
def get(self, user): # get the title of the post k = self.request.get('key', None) if k is None: self.redirect('/') return try: # get the post please post = Key(urlsafe=k).get() except: # key is invalid post = None # unnatural nav if post is None: self.r(flashes=flash('Post does not exist')) return # check if the user is the owner or not if post.author != user: self.redirect('/') return # get the form ready form = PostEditForm(data={ 'csrf_token': self.generate_csrf(), 'key': k, 'title': post.title, 'subject': post.subject, 'content': post.content }) self.r(form, post)
def get(self): """ Obtains user data for a list of user id's Method: GET Path: /users Request Parameters: accessToken string token required to gain access to the resource users JSON array id's of the users pretty [true|false] whether to output in human readable format or not Returns: :return: a list with the data of the requested users """ users_data = self.request.get('users') if users_data is '': self.write_signed_error(400, 'No users data was provided') try: user_keys = [] for user_id in loads(users_data): user_keys.append(Key(User, user_id)) query = User.query(User.key.IN(user_keys)) result = [] for user in query.fetch(): result.append({ 'id': user.key.id(), 'countryCode': user.country_code, 'rank': user.rank }) self.write_signed_message(200, 'users', result) except ValueError: self.write_signed_error(400, 'Malformed JSON') except AttributeError: self.write_signed_error(400, 'Invalid data')
def _objectToGDSDocument(aSource, aBaseGDSDocument = None): retval = None if IsDict(aSource): if aBaseGDSDocument: retval = aBaseGDSDocument else: retval = GDSDocument() for lkey, lvalue in aSource.iteritems(): if lkey == "key": retval.key = Key(GDSDocument, lvalue) else: lchildBaseDocument = None if aBaseGDSDocument and IsDict(aBaseGDSDocument) and lkey in aBaseGDSDocument: lchildBaseDocument = aBaseGDSDocument[lkey] lconvertedValue = _objectToGDSDocument(lvalue, lchildBaseDocument) retval.populate(**{lkey: lconvertedValue}) elif IsList(aSource): if IsListOfSimpleValues(aSource): retval = aSource else: retval = GDSJson(json = aSource) else: lneedTextBlob = isinstance(aSource, (str, unicode)) and sys.getsizeof(aSource) >= 500 if lneedTextBlob: retval = GDSTextBlobWrapper(text = aSource) else: retval = aSource return retval
def get(self, user): # grab title from URL k = self.request.get('key', None) # no key? no problem if k is None: self.redirect('/') return # does the post actually exist?? post = Key(urlsafe=k).get() if post is None: self.redirect('/') return # the post exists, is it owned by the user? if post.author != user: self.redirect('/') return # owned by user and exists. Good. form = PostDeleteForm(data={ 'csrf_token': self.generate_csrf(), 'key': post.key.urlsafe() }) self.r(form, post)
def editmod(mod_id): form = request.json mod = Key("Mod", mod_id, parent=TypeGroup.product_ancestor()).get() if mod is None: abort(404) if request.method == "POST": try: mod.name = form.get('name', mod.name) mod.tag = form.get('tag', mod.tag) mod.description = form.get('description', mod.description) mod.pre_add = form.get('pre_add', mod.pre_add) mod.multiplier = form.get('multiplier', mod.multiplier) mod.post_add = form.get('post_add', mod.post_add) mod.modifies = form.get('modifies', mod.modifies) mod.divides = form.get('divides', mod.divides) mod.rounding = form.get('rounding', mod.rounding) except: return jsonify({"messsages": ["Improper datafields"]}, 402) try: mod.put() except BadValueError as e: return jsonify({"messages": [e.message]}, 400) return jsonify(mod) return render_template('tantalus_mod.html', mod=mod)
def games_history(self, request): """ JWT required. Retrieves user's completed games starting from the provided offset, or 0. Limit 10 """ offset = request.offset payload = token.decode_jwt(request.jwt_token) try: user_key = Key(urlsafe=payload.get('user_key')) except TypeError: raise endpoints.BadRequestException( 'key was unable to be retrieved') except ProtocolBufferDecodeError: raise endpoints.BadRequestException( 'key was unable to be retrieved') except Exception as e: raise endpoints.InternalServerErrorException( 'An error occurred when attempting to retrieve user\'s games') try: games = Game.query( AND( OR(Game.player_one == user_key, Game.player_two == user_key), Game.game_completed == True)).order(-Game.date_created).fetch(offset=offset, limit=10) return UserGamesHistoryResponseForm(games=[ GamesHistory(player_one=game.player_one_name, player_two=game.player_two_name, game_key=game.key.urlsafe()) for game in games ]) except Exception as e: raise endpoints.InternalServerErrorException( 'An error occurred while retrieving completed games')
def get(self, request, key): text = Key(urlsafe=key).get() if not text: return HttpResponseNotFound() if not text.password and self._has_read_permission(text): return self._render_image(text) return HttpResponseForbidden()