我怎么优化这段Google App Engine代码?
我对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资源。
我应该从哪里入手进行改进呢?
6 个回答
2
你可以通过把完整的 self.request.get('links')
存储在数据库的一个文本字段中,来大幅减少你的应用和数据库之间的互动。
- 每次
post(self)
只需要一次put()
- 哈希值不会为每个链接重复存储,这样做没有意义,而且真的浪费空间
而且,当有人访问这个页面时,你也省去了对文本字段进行解析的麻烦……
3
我觉得这个代码看起来有点紧凑。
我注意到一个地方,可能会让它稍微好一点。
你在调用“self.request.get('links')”的时候用了两次。
所以可以加上:
unsplitlinks = self.request.get('links')
而且引用“unsplitlinks”可能会有帮助。
除此之外,我觉得循环是唯一一个可以优化的地方。
有没有可能先准备好数据,然后一次性添加到数据库,而不是每个链接都单独添加?(我猜 .put() 命令是把链接添加到数据库的)
7
这里主要的问题是你对数据存储的操作太多了。尽量把链接作为一个整体存储,就像Andre建议的那样。你可以把链接分开,放进一个数组里,然后存储到一个列表属性中。
如果你确实需要为每个链接创建一个单独的实体,可以试试这个方法:
# 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使用率飙升的原因。