优化Google App Engine代码

3 python optimization google-app-engine

Google应用引擎告诉我优化此代码.任何人有什么想法我能做什么?

def index(request):
    user = users.get_current_user()
    return base.views.render('XXX.html', 
                 dict(profiles=Profile.gql("").fetch(limit=100), user=user))
Run Code Online (Sandbox Code Playgroud)

后来我在模板中做了:

{% for profile in profiles %}
  <a href="/profile/{{profile.user.email}}/"><img src="{{profile.gravatarUrl}}"></a>
  <a href="/profile/{{profile.user.email}}/">{{ profile.user.nickname }}</a>
  <br/>{{ profile.shortDisplay }}
Run Code Online (Sandbox Code Playgroud)

使用的方法是:

def shortDisplay(self):
    return "%s/day; %s/week; %s days" % (self.maxPerDay, self.maxPerWeek, self.days)

def gravatarUrl(self):
    email = self.user.email().lower()
    default = "..."
    gravatar_url = "http://www.gravatar.com/avatar.php?"
    gravatar_url += urllib.urlencode({'gravatar_id':hashlib.md5(email).hexdigest(), 
        'default':default, 'size':"64"})
    return gravatar_url
Run Code Online (Sandbox Code Playgroud)

Nic*_*son 6

高CPU使用率将是由于每个请求获取100个实体.你有几个选择:

  • 使用Profile.all().fetch(100)将会更快,更容易阅读.
  • 从Profile模型中删除任何无关的属性.反序列化实体具有重要的每个属性开销.
  • 每页显示的用户更少.
  • 将此页面的输出存储在memcache中,并尽可能从memcache进行渲染.这样,您不需要经常生成页面,因此如果CPU高,则无关紧要.