0

我是 python 和 GAE 的新手,我一直在尝试通过示例学习如何为我自己的项目使用任务队列、cron 和数据存储,但一点运气都没有。我试图从 YouTube 上的 Google Developers 教程视频中修改投票者代码: http ://www.youtube.com/watch? v=AM0ZPO7-lcE 可以在这里看到:http: //voterlator.appspot.com/

我意识到代码不完整,所以我决定尝试找出缺少的内容。我做了一些替换(例如,编程语言现在是乳制品)。教程代码中有一些事情没有解决。例如,变量 LANGUAGES 没有在任何地方指定。我不清楚数据模型如何从表单中提取语言的值并将它们用作键。

我不知道为什么它不起作用。我留下了一些我试图让它在那里工作的代码并将其注释掉。

这是 app.yaml:

application: voting
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /static/css
  static_dir: static/css

- url: /static/css/sunny
  static_dir: static/css/sunny

- url: /static/js
  static_dir: static/js

- url: /cron/tally
  script: main.app

- url: /.*
  script: main.app

这是 cron.yaml:

cron:
- description: vote tallying worker
  url: /cron/tally
  schedule: every 1 minutes

这是 queue.yaml

total_storage_limit: 120M
queue:
- name: votes
  mode: pull

这是main.py

import webapp2
from google.appengine.ext import db
from google.appengine.api import taskqueue
import os
import jinja2

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class Tally(db.Model):
    """Counting model"""

    count = db.IntegerProperty(default=0, required=True)
    #key_name = ['Milk', 'Butter', 'Cheese'] #added
    #key_name = db.StringProperty(choices=set(['Milk', 'Butter', 'Cheese'])) #added
    cls = ['Milk', 'Butter', 'Cheese'] #added

    @classmethod
    def increment_by(cls, key_name, count):
        """Increases a tally's count. Should be run in a transaction."One tally for each language"""
        """The key_name is going to be the language name"""
        """There's a convenience method there that actually will update the count"""

        tally = cls.get_by_key_name(key_name)
        if tally is None:
            tally = cls(key_name=key_name)
        tally.count += count
        tally.put()
    #db.run_in_transaction(increment_by, key_name, count) #added
        #db.run_in_transaction(cls, key_name, count) #added

    #db.run_in_transaction(Tally.increment_by, cls, count) #added

class VoteHandler(webapp2.RequestHandler):
    """Handles adding of vote tasks"""
    def get(self):
        """Displays the voting form"""


        tally_query = Tally.all() #added
        #tally_query = Tally.all(key_name)   #added  
        tallies = tally_query.fetch(3) #added

        urla = '_ah/admin/'
        url_admin = 'Admin'

        urlvh = '/'
        url_votehand = 'Votes'

        ugliest = self.request.get('ugliest')

        template_values = {
            'tallies': tallies, #added
            'ugliest': ugliest, #added               

            'url_admin': url_admin,
            'urla': urla,

            'urlvh': urlvh,
            'url_votehand': url_votehand,
        }
        template = jinja_environment.get_template('vote_handler.html')
        self.response.out.write(template.render(template_values))
    def post(self):
        """Adds to the votes queue if ugliest is valid. """

        LANGUAGES = ['Milk', 'Butter', 'Cheese'] #added: This is just a guess

        ugliest = self.request.get('ugliest')
        if ugliest and ugliest in LANGUAGES:  ### No variable specified for LANGUAGES
            q = taskqueue.Queue('votes')
            q.add(taskqueue.Task(payload=ugliest, method='PULL'))

        self.redirect('/')

    #db.run_in_transaction(Tally.increment_by(cls, key_name, count)) #added

class TallyHandler(webapp2.RequestHandler):
    def post(self):
        """Leases vote tasks, accumulates tallies and stores them"""
        q = taskqueue.Queue('votes')
        # Keep leasing tasks in a loop.
        while True:
            tasks = q.lease_tasks(300, 1000)
            if not tasks:
                return
            # accumulate tallies in memory
            tallies = {}
            for t in tasks:
                tallies[t.payload] = tallies.get(t.payload, 0) + 1
            self.store_tallies(tallies)
            q.delete_tasks(tasks)

app = webapp2.WSGIApplication([('/', VoteHandler),
                               ('/cron/tally', TallyHandler)], #called from cron, pulls votes from the queue and updating tallies
                          debug=True)



def main():
    app.run()

if __name__ == "__main__":
    main()

这是 vote_handler.html 中表单的代码:

<form action="/" method="post">
<input type="radio" name="ugliest" value="Milk" /> Milk<br>
<input type="radio" name="ugliest" value="Butter" /> Butter<br>
<input type="radio" name="ugliest" value="Cheese" /> Cheese
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>

<div class="commentary">
    {% for tally in tallies %}
      {{ tally.count }}
    {% endfor %}
</div>

我试图让它在表单下方显示结果。

最终发生的事情是表单将任务添加到队列中,并且数据存储中有一个任务类型,但其中没有任何实体。我不知道出了什么问题。

4

1 回答 1

0

TallyHandler 的“put”方法应该重命名为“get”。(一个 cron 作业将调用一个 URL,使用一个 HTTP GET 请求。)

请注意,cron 任务不会在开发环境中自动运行,只会在生产环境中运行。使用管理控制台手动触发 cron 任务。

需要定义 store_tallies 方法。请参阅http://google-app-engine-samples.googlecode.com/svn/trunk/voterlator/上的原始源代码

顺便说一句,在 app.yaml 中,我建议使用限制对您的 cron URL 的访问

login: admin
于 2013-01-28T23:57:17.943 回答