我想模仿常见的CMS平台(如Wordpress或Drupal)的“已发布/未发布”功能。
所以我有这个Job(ndb.Model):
class Job(ndb.Model):
title = ndb.StringProperty()
published = ndb.StringProperty(default = "on")
created = ndb.DateTimeProperty(auto_now_add = True)
expire = ndb.DateTimeProperty()
NewJob处理程序如下所示:
class NewJob(JobHandler):
def get(self):
self.render('new-job.html')
def post(self):
title = self.request.get('title')
published = "on"
expire = datetime.datetime.now() + datetime.timedelta(days = 30)
if title:
j = Job(
title = title,
published = published,
expire = expire,
created = created)
j.put()
self.redirect('/job/%s' % str(j.key.id()))
else:
self.redirect('/login')
保存的实体看起来像这样:
Job(key=Key('Job', 5910974510923776), created=datetime.datetime(2014, 1, 17, 19, 0, 52, 12379), expire=datetime.datetime(2014, 2, 17, 19, 1, 52, 12174), published=u'on', title=u'Sous Chef')
我的目标是将所有Job
个实体设置为'发布==“关闭”'当他们expire
时间今天(现在)
所以我在cron.yaml
中设置了一个任务cron:
- description: expire job entities after 30 days
url: /cron/job-expire
schedule: every day 00:00
... /cron/job-expire
网址由:
class CronJobExpire(BaseHandler):
def get(self):
jobs = Job.query(Job.published == "on").fetch()
now = datetime.datetime.now()
for job in jobs:
if job.expire < now or job.expire == now:
job.published = "off"
上面CronJobExpire
处理程序的目的是:
检查当前published == "on"
的作业实体列表
检查他们的expire
日期是“now
”还是“< now
”,如果这是真,请设置published == "off"
。
这不起作用。我正在关注文档。任何帮助将不胜感激 - 谢谢。
答案 0 :(得分:2)
您需要保存更改的作业:
class CronJobExpire(BaseHandler):
def get(self):
jobs = Job.query(Job.published == "on").fetch()
now = datetime.datetime.now()
for job in jobs:
if job.expire <= now:
job.published = "off"
job.put()
另外,我建议只获取过期的工作:
now = datetime.datetime.now()
jobs = Job.query(Job.published == "on", Job.expire <= now).fetch()
for job in jobs:
job.published = "off"
job.put()
或者,减少API调用,从而提高速度:
now = datetime.datetime.now()
jobs = Job.query(Job.published == "on", Job.expire <= now).fetch()
for job in jobs:
job.published = "off"
ndb.put_multi(jobs)
最后,考虑将Job.published设为布尔值:
published = ndb.BooleanProperty(default=True)