2008-10-30 123 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