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 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 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
class ConferenceRoom: def __init__(self, kwargs): self.args = kwargs # self.room = getModel('conferencerooms', kwargs) Id = kwargs.get('id', None) if (Id == None) or (len(Id.strip()) == 0): self.room = conferencerooms() else: self.room = Key("conferencerooms", int(Id)).get() def create(self): room = self.args.get('room', None) if (room != None) or (len(room.strip()) > 0): self.room.room = room self.room.put() return {'id' : str(self.room.key.id())} else: return {'error' : 'room name cannot be null / empty'} def list(self): return self.room.query() def update(self): self.room.room = self.args.get('roomname', self.room.room) self.room.put() def delete(self): self.room.key.delete()
def decorated_view(*args, **kwargs): if request.method=='POST': code=request.form['code'] message=request.form['message'] url=request.form['url'] time=request.form['time'] # sign=request.form['sign'] else: code=request.args['code'] message=request.args['message'] url=request.args['url'] time=request.args['time'] # sign=request.args['sign'] logging.info(url) m = re.match(r'/(.*)/(.*)\.(.*)', url) if m: key=m.group(2) v=memcache.get(key) if v and v==url: logging.info('bump') else: campaign=Key(urlsafe=m.group(1)).get() qrcode=Key(urlsafe=key).get() suffix=m.group(3) qrcode.redirect=UPYUN_URL.format(UPYUN_BUCKET, m.group(1), m.group(2), suffix) qrcode.target=TARGET_CDN qrcode.put() memcache.set(key, url) kwargs['key']=key return func(*args, **kwargs)
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 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 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 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 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 post(self, category_key): form = self.get_form(category_key) if form.validate_on_submit(): for changed in set(form.activities.default).symmetric_difference(set(form.activities.data)): activity = Key(urlsafe=changed).get() if changed in form.activities.data: activity.tracked = True else: activity.tracked = False activity.put() flash('Update successful', category='success') return redirect(api.url_for(Activities, category_key=category_key)) flash('Update not successful', category='warning') return self.response('track/track_activity.html', form, category_key)
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 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 post(self): # Upload as a blob post_safekey = self.request.get('post') logging.info("Downloading media from post url") post = Key(urlsafe=post_safekey).get() if post: result = urlfetch.fetch(post.media_url) if result.status_code == 200: post.media_url, post.media_key = store_picture_from_content(result.content, result.headers['content-type']) post.put() logging.info("Post media uploaded to url {}".format(post.media_url)) else: logging.error("Error downloading {} - {}".format(post.media_url, result.status_code)) else: logging.info("Post not found: {}".format(post_safekey))
def editrelation(relation_id): form = request.json or request.form relation = Key("Relation", relation_id, parent=TypeGroup.relation_ancestor()).get() if request.method == "POST": relation.name = form.get('name', relation.name) relation.email = form.get('email', relation.email) relation.budget = form.get('budget', relation.budget) relation.has_budget = form.get('has_budget', relation.has_budget) relation.send_mail = form.get('send_mail', relation.send_mail) relation.put() return jsonify(relation) return render_template('tantalus_relation.html', relation=relation)
def tricky_stuff(): for prd in data["sell"]: product = Key('Product', int(prd['id']), parent=TypeGroup.product_ancestor()).get() if product is None: raise OperationError( "Product with id {} does not exist.".format(product)) line = product.take(int(prd['amount'])) product.put() for mod in prd["mods"]: mod_obj = Key('Mod', int(mod), parent=TypeGroup.product_ancestor()).get() if mod_obj is None: raise OperationError( "Mod with id {} does not exist.".format(mod)) mod_obj.apply(line) t.one_to_two.append(line) for prd in data["buy"]: product = Key('Product', int(prd['id']), parent=TypeGroup.product_ancestor()).get() if product is None: raise OperationError( "Product with id {} does not exist.".format(product)) line = TransactionLine(product=product.key, amount=int(prd['amount']), value=int(prd['price'])) for mod in prd["mods"]: mod_obj = Key('Mod', int(mod), parent=TypeGroup.product_ancestor()).get() if mod_obj is None: raise OperationError( "Mod with id {} does not exist.".format(mod)) mod_obj.apply(line) product.give(line) product.put() t.two_to_one.append(line)
def post(self, user): # grab the form form = CommentForm(self.request.params) if not form.validate(): form.csrf_token.data = self.generate_csrf() self.r(form) return # get the comment try: comment = Key(urlsafe=form.key.data).get() except: # invalid key comment = None if comment is None: self.redirect('/') return if comment.author != user: self.redirect('/') return # better be a post here or else! post = comment.key.parent().get() if post is None: self.redirect('/') return # update the comment try: comment.content = form.comment.data comment.put() self.redirect('/post/view?key=%s' % post.key.urlsafe()) return except: # let's give them another chance form.csrf_token.data = self.generate_csrf() self.r(form, flashes=flash()) return
def post(self, user): # grab the form form = PostEditForm(self.request.params) # 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 # validate form if not form.validate(): self.r(form) return # get the post please post = Key(urlsafe=form.key.data).get() 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 try: t = form.title.data post.title = t post.title_lower = lower(t) post.subject = form.subject.data post.content = form.content.data post.put() self.redirect('/author/%s' % post.author) return except Exception as e: form.csrf_token.data = self.generate_csrf() self.r(form) return
def fetch_pages_for_user(self): user = Key(urlsafe=self.request.get('key')).get() fetch_pages(user) user.last_fetched = datetime.now() user.put()
def sow(): qrcode=Key(urlsafe='aglzfmsyY2FjaGVyDgsSBlFSQ29kZRilsCQM').get() qrcode.note=u'那一天我二十一岁,在我一生的黄金时代。我有好多奢望。我想爱,想吃,还想在一瞬间变成天上半明半暗的云。后来我才知道,生活就是个缓慢受锤的过程,人一天天老下去,奢望也一天天消失,最后变得像挨了锤的牛一样。可是我过二十一岁生日时没有预见到这一点。我觉得自己会永远生猛下去,什么也锤不了我。' qrcode.target=1 qrcode.put() return 'OK'
def edit_transaction(t, data): # Easy stuff first # Note, this does not take care of money in budgets, do outside! Something with transactional limitations... t.revision += 1 if "deliverydate" in data: t.deliverydate = datetime.strptime(data["deliverydate"], "%Y-%m-%d").date() if "description" in data: t.description = data["description"] newsell = [] for prd in data["sell"]: product = Key('Product', int(prd['id']), parent=TypeGroup.product_ancestor()).get() if product is None: raise OperationError( "Product with id {} does not exist.".format(product)) line = TransactionLine(value=0, amount=int(prd['amount']), product=product.key) product.put() for mod in prd["mods"]: mod_obj = Key('Mod', int(mod), parent=TypeGroup.product_ancestor()).get() if mod_obj is None: raise OperationError( "Mod with id {} does not exist.".format(mod)) line.mods.append(mod_obj.key) newsell.append(line) t.one_to_two = transform_collection(t.one_to_two, newsell, True) newbuy = [] for prd in data["buy"]: product = Key('Product', int(prd['id']), parent=TypeGroup.product_ancestor()).get() if product is None: raise OperationError( "Product with id {} does not exist.".format(product)) line = TransactionLine(product=product.key, amount=int(prd['amount']), value=int(prd['price'])) for mod in prd["mods"]: mod_obj = Key('Mod', int(mod), parent=TypeGroup.product_ancestor()).get() if mod_obj is None: raise OperationError( "Mod with id {} does not exist.".format(mod)) mod_obj.apply(line) newbuy.append(line) t.two_to_one = transform_collection(t.two_to_one, newbuy, False) t.services = [] for prd in data["service"]: line = ServiceLine(service=prd['contenttype'], amount=int(prd['amount']), value=int(prd['price'])) t.services.append(line) t.total = transaction_total(t) t.put() return t
class identity(): def __init__(self, currentUser, Id = None): self.currentUser = currentUser if (Id == None) or (len(Id.strip()) == 0): self.identity = identities() else: self.identity = Key('identities',int(Id)).get() self.history = identityHistory() def create(self, user): logging.info("Creating User %s %s with UserId %s" % (user['firstName'], user['lastName'], user['email'])) self.identity.FirstName = user['firstName'] self.identity.LastName = user['lastName'] self.identity.EmailAddress = user['email'] self.identity.Password = user['password'] self.identity.put() self.updateHistory('Create') def list(self): return self.identity.query() def update(self, user): logging.info("Updating User %s %s with UserId %s" % (self.identity.FirstName, self.identity.LastName, self.identity.EmailAddress)) self.identity.FirstName = user['firstName'] self.identity.LastName = user['lastName'] self.identity.EmailAddress = user['email'] self.identity.Password = user['password'] self.identity.put() self.updateHistory('Update') def delete(self): logging.info("Deleting User %s %s with UserId %s" % (self.identity.FirstName, self.identity.LastName, self.identity.EmailAddress)) self.updateHistory('Delete') self.identity.key.delete() def updateHistory(self, action): logging.info("updating user history for %s" % (self.identity.FirstName)) self.history.IdentityId = str(self.identity.key.id()) self.history.FirstName = self.identity.FirstName self.history.LastName = self.identity.LastName self.history.EmailAddress = self.identity.EmailAddress self.history.Password = self.identity.Password self.history.Action = action self.history.Actor = self.currentUser self.history.put() def getUser(self): return self.identity def getUserId(self): return self.identity.EmailAddress def getFirstName(self): return self.identity.FirstName def getLastName(self): return self.identity.LastName def getUserById(self): currentuser = "" userqry = identities.query(identities.EmailAddress == self.currentUser) for user in userqry: currentuser = user break return currentuser
def logout(self, sessionId): logging.info("logging out") session = Key('sessions',int(sessionId)).get() session.ExpiresAt = datetime.now() session.put()
def complete_turn(self, request): """ JWT required. This will complete the provided turn. Expects to get the string representation of the cell to score e.g. "twos, sm_straight, full_house, etc..." """ game_key = request.game_key allocate_to = request.allocate_to payload = token.decode_jwt(request.jwt_token) try: user = Key(urlsafe=payload.get('user_key')) game = Key(urlsafe=game_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 complete the turn') turncard = TurnCard.query(TurnCard.owner == user, TurnCard.game == game).get() if turncard is None: raise endpoints.BadRequestException( 'Turn does not exist for the provided game') if turncard.owner != user: raise endpoints.UnauthorizedException( 'User is not associated with the provided game') total_turns = len(turncard.turns) if total_turns < 1: raise endpoints.BadRequestException( 'You should begin a turn before trying to complete one') # doesn't matter what turn this is, as long as it exists, and it hasn't been allocated, we can try to # allocate it to the game current_turn = turncard.turns[total_turns - 1].get() if current_turn.allocated_to is not None: raise endpoints.BadRequestException( 'This turn has already been completed') try: game = game.get() if game is None: raise endpoints.BadRequestException('This game does not exist') # game exists, so let's try to allocate this if game.player_one == user: score_player_one(allocate_to, game, current_turn) elif game.player_two == user: score_player_two(allocate_to, game, current_turn) game.player_two_last_turn_date = datetime.now() else: raise endpoints.BadRequestException( 'The user provided is not associated with this game') if total_turns == 13: # game is finished! complete_game(game, user) game.put() current_turn.put() return message_types.VoidMessage() except exceptions.AlreadyAssignedError as e: raise endpoints.BadRequestException(e.message) except Exception as e: # print e.message raise endpoints.InternalServerErrorException( 'An error occurred when attempting to complete the turn')
def fetch_page_threads(self): page = Key(urlsafe=self.request.get('key')).get() next_url = self.request.get('next_url') fetch_threads(page, next_url) page.last_fetched = datetime.now() page.put()