Exemplo n.º 1
0
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())
Exemplo n.º 2
0
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())
Exemplo n.º 3
0
                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
Exemplo n.º 4
0
 def __evento_o_fallo(eid):
     try:
         k = Key(urlsafe=(eid if '/' not in eid else eid[0:-1]))
         if not k.get():
             raise AgendamlgNotFoundException.evento_no_existe(eid)
         return k
     except Exception:
         raise AgendamlgNotFoundException.evento_no_existe(eid)
Exemplo n.º 5
0
def get_user(user_id):
    user_key = Key(User, user_id)
    user = user_key.get()

    if not user:
        return 'User not found!', 404

    return jsonify(_to_dict(user))
Exemplo n.º 6
0
  def fetch_page(self):
    key = Key(urlsafe=self.request.get('key'))
    page = key.get()

    fetch_feed(page)
    fetch_threads(page)

    page.last_fetched = datetime.now()
    page.put()
Exemplo n.º 7
0
 def _get_profile(self, params):
     try:
         profile_name = params.get("profile_name").lower()
         if not profile_name:
             raise ValueError()
         key = Key(models.Profile, profile_name)
         model = key.get()
         if not model:
             raise ValueError()
         return model
     except (KeyError, ValueError):
         raise webapp2.abort(404, "Profile not found")
Exemplo n.º 8
0
    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
                }))
Exemplo n.º 9
0
def _get_app_private_key():
    global APPLICATION_PRIVATE_KEY
    if not APPLICATION_PRIVATE_KEY:
        db_key = Key(ApplicationPrivateKey, "PrivateKey")
        private_key = db_key.get()
        if private_key is None:
            private_key = ApplicationPrivateKey(
                secret_bytes=Random.get_random_bytes(20))
            private_key.key = db_key
            print("Storing a new private key in the datastore")
            private_key.put()
        APPLICATION_PRIVATE_KEY = private_key
    return APPLICATION_PRIVATE_KEY
Exemplo n.º 10
0
    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}))
Exemplo n.º 11
0
def update_user(user_id):
    user_key = Key(User, user_id)
    user = user_key.get()

    lat = random.random() * 180 - 90
    lng = random.random() * 360 - 180

    if not user.location:
        user.location = Location()

    user.location.lat = lat
    user.location.lng = lng

    user.put()

    return jsonify(_to_dict(user))
Exemplo n.º 12
0
    def ConstructFromDict(cls, aDict, aReplace=True):
        aDenormalizedDict = UpdateDenormalizedObjectLinking(aDict)
        
        
        if aReplace:
            retval = DictToGDSDocument(aDenormalizedDict)
        else:
            lgdsDocument = None
            if aDict and IsDict(aDict) and "key" in aDict:
                lkeyid = aDict["key"]
                lkey = Key(GDSDocument, lkeyid)
                lgdsDocument = lkey.get()

            retval = DictToGDSDocument(aDenormalizedDict, lgdsDocument)
        
        return retval
Exemplo n.º 13
0
    def post(self):
        user_key = Key('User', self.session.get('user_key_id'))
        user_obj = user_key.get()

        self.session['dp_url'] = self.request.get('dp_url')
        self.session['email'] = self.request.get('email')
        self.session['f_name'] = self.request.get('first_name')
        self.session['l_name'] = self.request.get('last_name')

        user_obj.dp_url = self.request.get('dp_url')
        user_obj.email = self.request.get('email')
        user_obj.first_name = self.request.get('first_name')
        user_obj.last_name = self.request.get('last_name')
        user_obj.put()

        time.sleep(0.1)
        self.redirect('/profile')
Exemplo n.º 14
0
    def addActivity(self, request):
        #todo refactor , try optimize

        if (request.id):
            activityKey = Key(urlsafe=request.id)
            activity = activityKey.get()
            oldActivityCode = activity.code
            activity.code = request.code
            activity.name = request.name
            activity.tags = request.tags
            activity.defaultEventValue = request.defaultEventValue
            activity.thumbUrl = request.thumbUrl
            activity.put()

            #update existed items
            if (oldActivityCode != request.code):
                deferred.defer(update_events.UpdateEventActivityName,
                               users.get_current_user(), oldActivityCode,
                               request.code)

            return activityToMessage(activity)
        else:
            activityIter = Activity.query(
                ndb.AND(Activity.actor == users.get_current_user(),
                        Activity.code == request.code), ).iter(keys_only=True)

            if (activityIter.has_next()):
                activity = activityIter.next()
                activity.code = request.code
                activity.name = request.name
                activity.tags = request.tags
                activity.defaultEventValue = request.defaultEventValue
                activity.thumbUrl = request.thumbUrl
                activity.put()
                return activityToMessage(activity)
            else:
                activity = Activity(
                    actor=users.get_current_user(),
                    defaultEventValue=request.defaultEventValue,
                    name=request.name,
                    code=request.code,
                    tags=request.tags,
                    thumbUrl=request.thumbUrl)
                activity.put()
                return activityToMessage(activity)
Exemplo n.º 15
0
def sell():
    sale = request.json
    if not sale:
        return jsonify({"messages": ["No JSON supplied."]}, 400)

    try:
        prd = Key("PosProduct",
                  sale["product"],
                  parent=TypeGroup.product_ancestor())
        if prd.get() is None:
            raise BadValueError("Product does not exist")

        possale = PosSale(user=current_user.key,
                          product=prd,
                          amount=sale.get('amount', 1))
        possale.put()
    except (BadValueError, KeyError) as e:
        return jsonify({"messages": [e.message]}, 400)
    return jsonify(possale)
Exemplo n.º 16
0
    def get_person_info(self):
        try:
            key = Key(urlsafe=self.request.get("key"))
            person = key.get()

            # get total spend
            months = list(Month.query().filter(Month.people == key).fetch())
            total_spend = sum(month.average for month in months) * 1000

            # get payments made for every one
            money_usages = list(
                MoneyUsage.query().filter(MoneyUsage.person == key).fetch())
            payment = sum(money_usage.money_spend
                          for money_usage in money_usages) * 1000

            # last month
            if person.last_money_usage:
                last_money_usage = person.last_money_usage.get()
                last_month = last_money_usage.month.get()

                last_month_str = last_month.to_string_long()
                next_month_left = last_money_usage.next_month_left * 1000
                in_current_month = last_month.key == Month.get_current_month_key(
                )
            else:
                last_month_str = next_month_left = in_current_month = "N/A"

            # write
            s = ";".join(
                map(unicode, [
                    person.name,
                    key.id(), total_spend,
                    len(months), payment, last_month_str, next_month_left,
                    in_current_month
                ]))
            self.write(s)

        except Exception as e:
            print(e)
            self.response.status = 409
            self.write(
                "Can not resolve this buyer's key. Please reload this page or try again later"
            )
Exemplo n.º 17
0
 def recreate_api_user(self, api_user):
   auth.ensure_recognized_user(require_admin=True)
   if not api_user.email:
     raise Error("recreate_api_user: E-mail cannot be blank")
   db_key = Key(models.ApiUserModel, api_user.email)
   api_user_model = db_key.get()
   if api_user_model:
     if (api_user.secret and
         api_user_model.msg.secret != api_user.secret):
       raise Error("Can't set a custom secret. If you want a new one, just clear it and the server will generate a new one for you.")
   else:
     api_user_model = models.ApiUserModel(msg=api_user)
     api_user_model.key = db_key
   secret = api_user.secret
   if not api_user.secret:
     print("ckck: temp new token=" + auth.create_secret_token())
     api_user_model.msg.secret = auth.create_secret_token()
     print("ckck: new secret = " + api_user_model.msg.secret)
   api_user_model.put()
   return api_user_model.msg
Exemplo n.º 18
0
    def get(self, song_id=None):
        """
        Render the song lookup response page based on the urlsafe id parameter
        """
        template = JINJA_ENV.get_template('song.html')
        params = {}
        logging.info("Get song: {}".format(song_id))

        if not song_id:
            logging.debug("Blank id parameter.")
            params = {"msg": "Sorry! No match found."}
        else:
            song_key = Key(urlsafe=song_id)
            if song_key.id():
                params = {"song": song_key.get()}
                logging.debug("song key: {}\nsong: {}".format(str(song_key),
                                                              params["song"]))
            else:
                params = {"msg": "Invalid song ID."}

        self.response.write(template.render(**params))
Exemplo n.º 19
0
    def get(self, song_id=None):
        """
        Render the song lookup response page based on the urlsafe id parameter
        """
        template = JINJA_ENV.get_template('song.html')
        params = {}
        logging.info("Get song: {}".format(song_id))

        if not song_id:
            logging.debug("Blank id parameter.")
            params = {"msg": "Sorry! No match found."}
        else:
            song_key = Key(urlsafe=song_id)
            if song_key.id():
                params = {"song": song_key.get()}
                logging.debug("song key: {}\nsong: {}".format(
                    str(song_key), params["song"]))
            else:
                params = {"msg": "Invalid song ID."}

        self.response.write(template.render(**params))
Exemplo n.º 20
0
    def add(self, request):

        if (request.id):
            eventKey = Key(urlsafe = request.id)
            event = eventKey.get()
            event.actor = users.get_current_user()
            event.activityCode = (request.activity)
            event.comment = (request.comment)
            event.startTime = parseMsgTime(request.startTime)
            event.endTime = parseMsgTime(request.endTime)
            event.value = request.value
            event.put()
        else:
            event = Event(
                actor = users.get_current_user(),
                activityCode = (request.activity),
                comment = (request.comment),
                startTime = parseMsgTime(request.startTime), endTime = parseMsgTime(request.endTime),
                value = request.value)
            event.put()

        return eventToMessage(event)
Exemplo n.º 21
0
    def add(self, request):

        if (request.id):
            eventKey = Key(urlsafe=request.id)
            event = eventKey.get()
            event.actor = users.get_current_user()
            event.activityCode = (request.activity)
            event.comment = (request.comment)
            event.startTime = parseMsgTime(request.startTime)
            event.endTime = parseMsgTime(request.endTime)
            event.value = request.value
            event.put()
        else:
            event = Event(actor=users.get_current_user(),
                          activityCode=(request.activity),
                          comment=(request.comment),
                          startTime=parseMsgTime(request.startTime),
                          endTime=parseMsgTime(request.endTime),
                          value=request.value)
            event.put()

        return eventToMessage(event)
Exemplo n.º 22
0
def initialize(request):
    key = Key(Branch, "caba")
    if not key.get():
        Branch(key=key, name=u"Capital").put()
        u_roles = [roles.SECRETARY, roles.ADVISOR]
        User(parent=key,
             name=u"Juan Prueba",
             email="*****@*****.**",
             roles=u_roles).put()
        User(parent=key,
             name=u"Augusto D'Amario",
             email="*****@*****.**",
             roles=u_roles).put()
        User(parent=key,
             name=u"Julio Veronelli",
             email="*****@*****.**",
             roles=u_roles).put()
        User(parent=key,
             name=u"Hernán Acosta",
             email="*****@*****.**",
             roles=u_roles).put()
    return "OK"
Exemplo n.º 23
0
 def recreate_api_user(self, api_user):
     auth.ensure_recognized_user(require_admin=True)
     if not api_user.email:
         raise Error("recreate_api_user: E-mail cannot be blank")
     db_key = Key(models.ApiUserModel, api_user.email)
     api_user_model = db_key.get()
     if api_user_model:
         if (api_user.secret
                 and api_user_model.msg.secret != api_user.secret):
             raise Error(
                 "Can't set a custom secret. If you want a new one, just clear it and the server will generate a new one for you."
             )
     else:
         api_user_model = models.ApiUserModel(msg=api_user)
         api_user_model.key = db_key
     secret = api_user.secret
     if not api_user.secret:
         print("ckck: temp new token=" + auth.create_secret_token())
         api_user_model.msg.secret = auth.create_secret_token()
         print("ckck: new secret = " + api_user_model.msg.secret)
     api_user_model.put()
     return api_user_model.msg
Exemplo n.º 24
0
    def addActivity(self, request):
        #todo refactor , try optimize

        if (request.id):
            activityKey = Key(urlsafe = request.id)
            activity = activityKey.get()
            oldActivityCode = activity.code
            activity.code = request.code
            activity.name = request.name
            activity.tags = request.tags
            activity.defaultEventValue = request.defaultEventValue
            activity.thumbUrl = request.thumbUrl
            activity.put()

            #update existed items
            if (oldActivityCode != request.code):
                deferred.defer(update_events.UpdateEventActivityName, users.get_current_user(), oldActivityCode, request.code)

            return activityToMessage(activity)
        else:
            activityIter = Activity.query(ndb.AND(
                        Activity.actor == users.get_current_user(),
                        Activity.code == request.code),
                        ).iter(keys_only=True)

            if (activityIter.has_next()):
                activity = activityIter.next()
                activity.code = request.code
                activity.name = request.name
                activity.tags = request.tags
                activity.defaultEventValue = request.defaultEventValue
                activity.thumbUrl = request.thumbUrl
                activity.put()
                return activityToMessage(activity)
            else:
                activity = Activity(actor = users.get_current_user(), defaultEventValue = request.defaultEventValue, name = request.name, code = request.code, tags = request.tags, thumbUrl = request.thumbUrl)
                activity.put()
                return activityToMessage(activity)
Exemplo n.º 25
0
    def post(self, params):
        try:
            model = self._get_model(params)
        except Exception:
            pass
        else:
            if model:
                raise webapp2.abort(400, "Profile already exists")

        profile_name = params.get("profile_name").lower()
        email = params.get("email").lower()
        if not profile_name or not email:
            raise ValueError("Please specify 'profile_name' and 'email'.")
        key = Key(models.Profile, profile_name)
        if key.get() is not None:
            raise ValueError("Profile already exists.")

        profile = models.Profile(key=key, owner_email=email, edit_key=uuid4().hex)

        mail.send_mail(sender="Benjamin Kampmann <*****@*****.**>",
              to=email,
              subject="Your miHats Admin Link",
              body="""
Hi there,

thanks for signing up for the miHats Hat-Sharing Webservice.
You can administer it at:

 http://amasoeany.appspot.com/#/{0}/{1}

DON'T share this link!

Best
Ben
""".format(profile_name, profile.edit_key))
        profile.put()
        return {"profile_name": profile_name, "key": profile.edit_key}
Exemplo n.º 26
0
    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')
Exemplo n.º 27
0
 def send_report(self):
   key = Key(urlsafe=self.request.get('key'))
   user = key.get()
   mail.send_report(user)
Exemplo n.º 28
0
 def id_exists(cls, model_id, namespace=None):
     key = Key(cls._get_kind(), model_id, namespace=namespace)
     return key.get() is not None
Exemplo n.º 29
0
def new_transaction(data, ):
    relation = Key('Relation',
                   int(data["relation"]),
                   parent=TypeGroup.relation_ancestor())
    if relation.get() is None:
        raise OperationError("Relation does not exist!")

    tr = Transaction.query(
        Transaction.relation == relation).order(-Transaction.reference).get()
    if tr is None:
        reference = 1
    else:
        reference = tr.reference + 1

    t = Transaction(revision=0,
                    reference=reference,
                    relation=relation,
                    deliverydate=datetime.strptime(data["deliverydate"],
                                                   "%Y-%m-%d").date(),
                    processeddate=datetime.now(
                        timezone("Europe/Amsterdam")).date(),
                    description=data.get("description", ""))

    @transactional(xg=True)
    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)

    tricky_stuff()
    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
Exemplo n.º 30
0
 def fromURLSafeKey(key):
     user_key = Key(urlsafe=key)
     return user_key.get()