5

我对 Python 世界比较陌生,但这似乎很简单。

谷歌对我大喊,这段代码需要优化:

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。

我应该在哪里寻找改进?

4

6 回答 6

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 上限的是往返次数。

于 2008-10-30T14:41:19.420 回答
3

对我来说看起来很紧。

我看到一件事可能会有所改善。你的电话,“self.request.get('links')”两次。

所以添加:

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

引用“未拆分链接”可能会有所帮助。

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

于 2008-10-30T14:13:15.717 回答
2

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

  • put()每人只有一个post(self)
  • 哈希没有存储 n 次(对于每个链接,这没有意义,真的是浪费空间)

当有人实际调用该页面时,您可以节省对文本字段的解析......

于 2008-10-30T14:22:26.557 回答
0

这多久被调用一次?这看起来还不错……尤其是在删除重复请求之后。

于 2008-10-30T14:21:41.130 回答
0

我可以查询 ListProperty 吗?

就像是

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

我有未来需要该功能的计划。

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

于 2008-10-30T14:58:50.977 回答
0

不/你不能使用像“links.contains(' http://www.google.com ')”这样的东西 GQL 不支持这个

于 2008-11-05T10:25:38.040 回答