1

在此示例代码中,应用程序的 URL 似乎由应用程序中的这一行决定:

application = webapp.WSGIApplication([('/mailjob', MailJob)], debug=True)

但也可以通过 app.yaml 的应用程序处理程序中的这一行:

- url: /.*
  script: main.py

但是,cron 任务的 URL 由以下行设置:

url: /tasks/summary

所以似乎 cron 实用程序将调用“ /tasks/summary”,并且由于应用程序处理程序,这将导致main.py被调用。这是否意味着,就 cron 而言,应用程序中设置 URL 的行是无关的:

application = webapp.WSGIApplication([('/mailjob', MailJob)], debug=True)

. . . 因为 cron 任务需要的唯一 URL 是 app.yaml 中定义的 URL。

app.yaml
application: yourappname
version: 1
runtime: python
api_version: 1

handlers:

- url: /.*
  script: main.py

cron.yaml
cron:
    - description: daily mailing job
    url: /tasks/summary
    schedule: every 24 hours

main.py
#!/usr/bin/env python  

import cgi
from google.appengine.ext import webapp
from google.appengine.api import mail
from google.appengine.api import urlfetch 

class MailJob(webapp.RequestHandler):
    def get(self):

        # Call your website using URL Fetch service ...
        url = "http://www.yoursite.com/page_or_service"
        result = urlfetch.fetch(url)

        if result.status_code == 200:
            doSomethingWithResult(result.content)

        # Send emails using Mail service ...
        mail.send_mail(sender="admin@gmail.com",
                to="someone@gmail.com",
                subject="Your account on YourSite.com has expired",
                body="Bla bla bla ...")
        return

application = webapp.WSGIApplication([
        ('/mailjob', MailJob)], debug=True)

def main():
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()
4

2 回答 2

3

你可以这样做:

app.yaml
application: yourappname
version: 1
runtime: python
api_version: 1

handlers:

- url: /tasks/.*
  script: main.py

cron.yaml
cron:
    - description: daily mailing job
    url: /tasks/summary
    schedule: every 24 hours

main.py
#!/usr/bin/env python  

import cgi
from google.appengine.ext import webapp
from google.appengine.api import mail
from google.appengine.api import urlfetch 

class MailJob(webapp.RequestHandler):
    def get(self):

        # Call your website using URL Fetch service ...
        url = "http://www.yoursite.com/page_or_service"
        result = urlfetch.fetch(url)

        if result.status_code == 200:
                doSomethingWithResult(result.content)

        # Send emails using Mail service ...
        mail.send_mail(sender="admin@gmail.com",
                        to="someone@gmail.com",
                        subject="Your account on YourSite.com has expired",
                        body="Bla bla bla ...")
        return

application = webapp.WSGIApplication([
        ('/tasks/summary', MailJob)], debug=True)

def main():
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()
于 2009-07-11T21:15:13.280 回答
1

看起来您正在阅读此页面(即使您没有向我们提供 URL)。显示的配置和代码将无法成功运行:cron 任务将尝试访问 URL 路径 /tasks/summary,app.yaml 将使其执行 main.py,但后者仅为 /mailjob 设置一个处理程序,所以cron 任务的尝试将失败并返回 404 状态码。

于 2009-07-11T20:48:59.963 回答