def save(self, user): cd = self.cleaned_data image_uri = ImageUtils.handle_weibo_image(cd['image']) if cd['image'] else None wb_cnt = WeiboContent.create( user_id=user.id, username=user.username, text=cd['text'], push_date=datetime.datetime.now(), image_uri=image_uri, ) return _send_weibo(user, wb_cnt)
def cron_delete(request, wbcnt_id): wb_cnt = WeiboContent.get_by_id(wbcnt_id) if not wb_cnt or wb_cnt.user_id != request.user.id: messages.success(request, u'错误的操作!') return HttpResponseRedirect(reverse('cron_unsent_list')) if request.method == 'POST': # FIXME: not good, get all jobs and iterate them scheduler = get_scheduler() jobs = scheduler.get_jobs() for job in jobs: if job.name == wbcnt_id: scheduler.unschedule_job(job) wb_cnt.delete() return HttpResponseRedirect(reverse('cron_unsent_list'))
def save(self, user): cd = self.cleaned_data _date = cd.get('send_date', datetime.datetime.now()) _hour = int(cd.get('hour', '0')) _minute = int(cd.get('minute', '0')) image_uri = ImageUtils.handle_weibo_image(cd['image']) if cd['image'] else None wb_cnt = WeiboContent.create( user_id=user.id, username=user.username, text=cd['text'], push_date=datetime.datetime(_date.year, _date.month, _date.day, _hour, _minute), image_uri=image_uri, ) _add_scehduler(_send_weibo, user, wb_cnt) return wb_cnt
def cron_add(request, template): if request.method == 'POST': form = CronForm(request.POST, request.FILES) if form.is_valid(): form.save(request.user) messages.success(request, u'添加推送微博任务成功') return HttpResponseRedirect(reverse('cron_add')) else: s_date = datetime.datetime.now() + datetime.timedelta(minutes=5) form = CronForm(initial={'send_date': s_date, 'hour': s_date.hour, 'minute': s_date.minute}) recent_cron = WeiboContent.find({'user_id': request.user.id}, sort=[('created', -1)], limit=1) return render_to_response(template, { 'form': form, 'recent_cron': recent_cron, }, context_instance=RequestContext(request))
# coding: utf-8 import datetime from apscheduler.scheduler import Scheduler from autowb.account.models import User from autowb.cron.models import WeiboContent def default_callback(user, wb_cnt): return user.update_weibo(wb_cnt) wb_cnt_unsent = WeiboContent.find({'sent': False, 'push_date': {'$gt': datetime.datetime.now()}}) # _scheduler = Scheduler(daemonic=False) _scheduler = Scheduler() # reload unsent job for wb_cnt in wb_cnt_unsent: user = User.get_by_id(wb_cnt.user_id) _scheduler.add_date_job(default_callback, date=wb_cnt.push_date, name=str(wb_cnt.id), args=[user, wb_cnt, ]) _scheduler.start() def get_scheduler(): return _scheduler
def cron_sent_list(request, template): all_unsent = [x for x in WeiboContent.find({'user_id': request.user.id, 'sent': True}, sort=[('push_date', -1)])] obj = get_paginator(request, all_unsent, 10) return render_to_response(template, { 'obj': obj, }, context_instance=RequestContext(request))