Exemple #1
0
 def init(self, key):
   self.recipe = get_or_404(models.Recipe, key)
   if self.recipe.disabled:
     return NotFound()
     
   if not (self.request.user.is_admin or self.request.user.key() == self.recipe.parent_key()):
     return Unauthorized()
   
   self.ingredients = models.RecipeIngr.all().ancestor(self.recipe).order('__key__').fetch(20)
   
   initial = {}
   initial['title'] = self.recipe.title
   initial['recipe'] = self.recipe.recipe
   initial['tags'] = ', '.join(self.recipe.tags)
   initial['category'] = self.recipe.category
   initial['phase'] = self.recipe.phase
   initial['type'] = self.recipe.type
   initial['ig'] = self.recipe.ig
   initial['time'] = self.recipe.time
   initial['rec_vis'] = self.recipe.rec_vis
   initial['ingr'] = [{
     'product': i.product,
     'portion': i.portion,
     'weight': i.weight
     } for i in self.ingredients]
   self.form = RecipeForm(initial, edit=True)
   if self.recipe.rec_vis == VISIBILITY[1]:
     self.form.rec_vis.choices = [VISIBILITY[1], VISIBILITY[2]]
   if self.recipe.rec_vis == VISIBILITY[2]:
     self.form.rec_vis.choices = [VISIBILITY[2]]
Exemple #2
0
 def prepare(self):
   initial = {}
   initial['rec_vis'] = self.request.user.rec_vis
   self.form = RecipeForm(initial)
Exemple #3
0
class RecipeAddHandler(LoginRequiredHandler):
  def prepare(self):
    initial = {}
    initial['rec_vis'] = self.request.user.rec_vis
    self.form = RecipeForm(initial)

  def get(self):
    return render_to_response('przepisy/add.html', {
      'form': self.form.as_widget(),
    })

  def post(self):
    if self.form.validate(self.request.form):
      try:
        # utwórz przepis
        recipe = models.Recipe(
          parent=self.request.user,
          key_name=slugify(self.form['title']),
          title=self.form['title'],
          recipe=self.form['recipe'],
          recipe_html=markdown2html(self.form['recipe']),
          tags=models.Tag.split_elements(self.form['tags']),
          category=self.form['category'],
          phase=self.form['phase'],
          type=self.form['type'],
          ig=self.form['ig'],
          time=int(self.form['time']),
          rec_vis=self.form['rec_vis'],
          ingr_count=len(self.form['ingr']),
          disabled=False
        )
        
        # zapisz dane przepisu
        recipe.put()
        
        # dodaj osobno skladniki
        # + AC składników
        ingr_to_save = []
        for i, ingr in enumerate(self.form['ingr']):
          ingr_to_save.append(models.RecipeIngr(parent=recipe, key_name='%2d'%(i+1), product=ingr['product'],
                            portion=ingr['portion'], weight=ingr['weight']))
          ingr_to_save.append(models.IngrACIndex(key_name=ingr['product'], idx=models.IngrACIndex.make_index(ingr['product'])))
          
        db.put(ingr_to_save)

        # uaktualnij użytkownika
        if recipe.rec_vis == VISIBILITY[2]:
          def utx():
            user = PMMUser.get(self.request.user.key())
            user.rec_pub += 1
            user.put()
            cache_delete('gfcu', self.request.user.key().name())
          db.run_in_transaction(utx)

        # Dodaj podwójny licznik...
        Counter.init_shards(SHARD_RECIPE_KEY % recipe.key(), 2) # 2 means about 15 writes/s per recipe 
        
        # na później odłóż indeksację, uaktualnienie tagów i licznika kategorii
        deferred_lib.defer(deferred.recipe_update, recipe.key(), 'add')

        # wyślij powiadomienie o dodaniu przepisu!
        if recipe.rec_vis != VISIBILITY[0]:
          try:
            create_activity(self.request.user.key().name(),
                            u'%s dodał(a) przepis <a href="%s">%s</a>' % (self.request.user.display_name, recipe.get_url(True), recipe.title),
                            u'Przejrzyj go, oceń lub dodaj do ulubionych.'
            )
          except Exception, e:
            pass
            
        self.request.notifications.success('Przepis dodany!')
        return redirect(recipe.get_url())
      except Exception, e:
        logging.exception('Recipe add failed (%s): ' % self.request.user + str(e))
        self.request.notifications.error('Przepisu nie dodano! Wystąpił błąd zapisu, spróbuj ponownie...')    
Exemple #4
0
class RecipeEditHandler(LoginRequiredHandler):
  def init(self, key):
    self.recipe = get_or_404(models.Recipe, key)
    if self.recipe.disabled:
      return NotFound()
      
    if not (self.request.user.is_admin or self.request.user.key() == self.recipe.parent_key()):
      return Unauthorized()
    
    self.ingredients = models.RecipeIngr.all().ancestor(self.recipe).order('__key__').fetch(20)
    
    initial = {}
    initial['title'] = self.recipe.title
    initial['recipe'] = self.recipe.recipe
    initial['tags'] = ', '.join(self.recipe.tags)
    initial['category'] = self.recipe.category
    initial['phase'] = self.recipe.phase
    initial['type'] = self.recipe.type
    initial['ig'] = self.recipe.ig
    initial['time'] = self.recipe.time
    initial['rec_vis'] = self.recipe.rec_vis
    initial['ingr'] = [{
      'product': i.product,
      'portion': i.portion,
      'weight': i.weight
      } for i in self.ingredients]
    self.form = RecipeForm(initial, edit=True)
    if self.recipe.rec_vis == VISIBILITY[1]:
      self.form.rec_vis.choices = [VISIBILITY[1], VISIBILITY[2]]
    if self.recipe.rec_vis == VISIBILITY[2]:
      self.form.rec_vis.choices = [VISIBILITY[2]]

  def get(self, key):
    ret = self.init(key)
    if ret:
      return ret

    return render_to_response('przepisy/edit.html', {
      'form': self.form.as_widget(),
    })

  def post(self, key):
    ret = self.init(key)
    if ret:
      return ret

    if self.form.validate(self.request.form):
      if self.form.has_changed:
        try:
          self.recipe.title = self.form['title']
          self.recipe.recipe = self.form['recipe']
          self.recipe.recipe_html = markdown2html(self.form['recipe'])
          self.recipe.phase = self.form['phase']
          self.recipe.type = self.form['type']
          self.recipe.ig = self.form['ig']
          self.recipe.time = int(self.form['time'])
          self.recipe.ingr_count = len(self.form['ingr'])
          
          new_tags = models.Tag.split_elements(self.form['tags'])
          tag_diff = models.Tag.find_differences(self.recipe.tags, new_tags)
          self.recipe.tags = new_tags
        
          if self.recipe.category != self.form['category']:
            category_diff = self.recipe.category, self.form['category']
          else:
            category_diff = ()
          self.recipe.category = self.form['category']
          
          if self.recipe.rec_vis != self.form['rec_vis']:
            rec_vis_diff = self.recipe.rec_vis, self.form['rec_vis']
          else:
            rec_vis_diff = ()
          self.recipe.rec_vis = self.form['rec_vis']
          
          # zapisz dane przepisu
          self.recipe.put()
          
          # usuń nadmiarowe składniki
          if len(self.ingredients) > len(self.form['ingr']):
            db.delete([db.Key.from_path('RecipeIngr', '%2d'%(i+1), parent=self.recipe.key()) for i in range(len(self.form['ingr']), len(self.ingredients))])
          
          # nadpisz istniejące lub dodaj nowe; dodaj AC składników, jeśli nowe
          ingr_to_save = []
          old_ingr_names = [i.product for i in self.ingredients]
          for i, ingr in enumerate(self.form['ingr']):
            ingr_to_save.append(models.RecipeIngr(parent=self.recipe, key_name='%2d'%(i+1), product=ingr['product'],
                              portion=ingr['portion'], weight=ingr['weight']))
            if ingr['product'] not in old_ingr_names:
              ingr_to_save.append(models.IngrACIndex(key_name=ingr['product'], idx=models.IngrACIndex.make_index(ingr['product'])))
          db.put(ingr_to_save)

          # uaktualnij użytkownika
          if rec_vis_diff and self.recipe.rec_vis != VISIBILITY[2]:
            def utx():
              user = PMMUser.get(self.request.user.key())
              user.rec_pub -= 1
              if user.rec_pub < 0:
                user.rec_pub = 0
              user.put()
              cache_delete('gfcu', self.request.user.key().name())
            db.run_in_transaction(utx) 
          elif rec_vis_diff and self.recipe.rec_vis == VISIBILITY[2]:
            def utx():
              user = PMMUser.get(self.request.user.key())
              user.rec_pub += 1
              user.put()
              cache_delete('gfcu', self.request.user.key().name())
            db.run_in_transaction(utx) 
          
          # na później odłóż indeksację, uaktualnienie tagów i licznika kategorii
          deferred_lib.defer(deferred.recipe_update, self.recipe.key(), 'update', tag_diff, category_diff, rec_vis_diff)
  
          # wyślij powiadomienie o dodaniu przepisu!
          if self.recipe.rec_vis != VISIBILITY[0]:
            try:
              create_activity(self.request.user.key().name(),
                              u'%s zmodyfikował(a) przepis <a href="%s">%s</a>' % (self.request.user.display_name, self.recipe.get_url(True), self.recipe.title),
                              u'Zobacz, co się zmieniło.'
              )
            except Exception, e:
              pass
              
          self.request.notifications.success('Zapisano zmodyfikowany przepis!')
          return redirect(self.recipe.get_url())
        except Exception, e:
          logging.exception('Recipe add failed (%s): ' % self.request.user + str(e))
          self.request.notifications.error('Przepisu nie zmieniono! Wystąpił błąd zapisu, spróbuj ponownie...')
      else: