我如何优化此Google App Engine代码? [英] How can I optimize this Google App Engine code?
问题描述
Google向我大声说这个代码需要优化:
I'm relatively new to the python world, but this seems very straight forward.
我对python世界相对陌生,但这看起来非常直截了当。 p>
Google is yelling at me that this code needs to be optimized:
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。
The dashboard is telling me that this is using a ton of CPU.
我应该在哪里寻找改进?
Where should I look for improvements?
推荐答案
这里的主要开销是多个单独放入数据存储。如果可以的话,按照Andre的说法,将链接存储为一个实体。您可以将链接始终分割成一个数组并将其存储在ListProperty中。
The main overhead here is the multiple individual puts to the datastore. If you can, store the links as a single entity, as Andre suggests. You can always split the links into an array and store it in a ListProperty.
如果您确实需要每个链接的实体,请尝试以下操作:
If you do need an entity for each link, try this:
# 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上限的往返次数。
It will reduce the datastore roundtrips to one, and it's the roundtrips that are really killing your high CPU cap.
这篇关于我如何优化此Google App Engine代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!