2014-01-18 47 views
0

我想模仿常見CMS平臺(如Wordpress或Drupal)的「已發佈/未發佈」功能。Google App Engine:使用cron過期(或「取消發佈」)實體

所以我有這個工作(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實體設置爲'publish =='off'',當它們的expire時間是今天(現在)

所以我成立了一個任務在cron.yaml

cron: 
- description: expire job entities after 30 days 
    url: /cron/job-expire 
    schedule: every day 00:00 

...和/cron/job-expire URL被處理:

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"

這不起作用。我正在關注文檔。任何幫助將不勝感激 - 謝謝。

回答

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) 
+0

傻了。感謝您提供更多建議。 – puoyaahhh