def _get_untweeted_tweet(key, user): tweet = ScheduledTweet.get(key) if tweet.user != user: raise Exception("User does not own Tweet") if tweet.tweeted: raise Exception("Tweet already Tweeted") return tweet
def batch_delete(request): tweets = ScheduledTweet.all() tweets.filter('tweeted =', True) # Delete all Tweets >= 1 day old. tweets.filter('created_at <=', datetime.utcnow() - timedelta(days=1)) for tweet in tweets: tweet.delete() return HttpResponse()
def save(request): user = request.user key = request.POST.get("key") if key: tweet = _get_untweeted_tweet(key, user) else: # Only check if user exceeded usage limits when new Tweet created, not when # editing existing one. if _too_many_tweets_sent(user): return HttpResponse("Too many Tweets sent.", status=403, content_type="text/plain") tweet = ScheduledTweet() properties = { "user": user, "tweet": request.POST.get("tweet"), "post_at": datetime.utcfromtimestamp(float(request.POST.get("post_at", 0))), "ip_address": request.META.get("REMOTE_ADDR"), } [setattr(tweet, property, properties[property]) for property in properties] tweet.put() return HttpResponse("Woohoo! Your Tweet has been scheduled.", content_type="text/plain")
def next_scheduled(request): from django.template import Context from django.template.loader import get_template tweet = ScheduledTweet.untweeted(request.user, descending=False).get() if tweet: template = get_template("_next_scheduled_tweet.html") content = template.render(Context({"tweet": tweet})) return JsonResponse({"content": content}) else: # HTTP status code must currently be 200 -- otherwise, jQuery's getJSON # won't execute my callback, thereby preventing me from handling the error. return JsonResponse({"error_code": "no_tweets_scheduled", "error_text": "No Tweets scheduled."})
def batch_send(request): tweets = ScheduledTweet.all() tweets.filter('post_at <=', datetime.utcnow()) tweets.filter('tweeted =', False) twitterer = Twitterer() for tweet in tweets: try: successfully_tweeted = twitterer.tweet(tweet) except Exception, e: # TODO: add e-mail notification (or some other handling) if tweet fails. Or perhaps # should simply notify whenever logging.error is called. logging.error('%s raised when sending Tweet %s: %s' % (repr(e), tweet, e)) else: if successfully_tweeted: tweet.tweeted = True tweet.put()
def _too_many_tweets_sent(user): tweets = ScheduledTweet.all() tweets.filter("user =", user) return tweets.count() >= 50
def view(request): tweets = ScheduledTweet.untweeted(request.user) return direct_to_template(request, "view_tweets.html", {"tweets": tweets})
def edit(request): return direct_to_template(request, "edit_tweet.html", {"tweet": ScheduledTweet.get(request.GET.get("key"))})