2008-10-30 126 views
5

我对Python世界比较陌生,但这看起来非常直截了当。如何优化此Google App Engine代码?

谷歌在我大呼小叫,需要进行优化验证码:

class AddLinks(webapp.RequestHandler): 
    def post(self): 
      # Hash the textarea input to generate pseudo-unique value 
      hash = md5.new(self.request.get('links')).hexdigest() 

      # Seperate the input by line 
      allLinks = self.request.get('links').splitlines() 

      # For each line in the input, add to the database 
      for x in allLinks: 
       newGroup = LinkGrouping() 
       newGroup.reference = hash 
       newGroup.link = x 
       newGroup.put() 

      # testing vs live 
      #baseURL = 'http://localhost:8080' 
      baseURL = 'http://linkabyss.appspot.com' 

      # Build template parameters 
      template_values = { 
       'all_links': allLinks, 
       'base_url': baseURL, 
       'reference': hash, 
      } 

      # Output the template 
      path = os.path.join(os.path.dirname(__file__), 'addLinks.html') 
      self.response.out.write(template.render(path, template_values)) 

仪表板是告诉我,这是使用一吨的CPU。

我应该在哪里寻求改进?

回答

7

这里的主要开销是对数据存储的多个单独放置。如果可以的话,按照Andre的说法,将链接存储为一个实体。您始终可以将链接拆分为数组并将其存储在ListProperty中。

如果你需要为每一个链路的实体,试试这个:

# For each line in the input, add to the database 
groups = [] 
for x in allLinks: 
    newGroup = LinkGrouping() 
    newGroup.reference = hash 
    newGroup.link = x 
    groups.append(newGroup) 
db.put(groups) 

它将数据存储往返减少到一个,而且它是真的杀死你的高CPU帽往返。

3

对我来说看起来很紧张。

我看到一件事情可能会有所改善。 你的调用,“self.request.get('链接')”两次。

因此增加:

unsplitlinks = self.request.get('links') 

和引用, “unsplitlinks” 可能会有帮助。

除此之外,循环是唯一的区域,我认为这将是优化的目标。 是否有可能准备数据,然后将其添加到数据库一次,而不是做每个链接的数据库添加? (我假设.put()命令将链接添加到数据库中)

0

这个调用的频率如何?这看起来并不坏......特别是在删除重复的请求后。

2

只需将完整的self.request.get('links')存储在数据库的文本字段中,就可以显着减少应用程序和数据库之间的交互。

  • 只有一个put()post(self)
  • 散列不被存储n次(对每一个环节,这是没有意义的,是很浪费空间)

你救自己当有人实际调用页面时解析文本字段...。

0

我可以查询ListProperty吗?

喜欢的东西

SELECT * FROM LinkGrouping WHERE links.contains('http://www.google.com') 

我未来的计划,我需要这个功能。

我肯定会实现单个db.put()来减少使用量。

+1

是,ListProperties有一个很酷的功能。如果您使用LinkGrouping.gql(“WHERE links =:1”,“http://www.google.com”),它将返回列表中包含“http://www.google.com”的所有群组。 – 2008-11-13 04:58:15