PageRenderTime 10ms CodeModel.GetById 1ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/comment_utils/bin/delete_spam_comments.py

http://django-comment-utils.googlecode.com/
Python | 93 lines | 86 code | 1 blank | 6 comment | 0 complexity | 97bc24b6ed29fa2d2b6eb472c46a8f82 MD5 | raw file
 1"""
 2A script which removes spam comments from the database.
 3
 4The determination of which comments are spam is based on two pieces of
 5information:
 6
 71. The comment's ``is_public`` field, and
 8
 92. The comment's age.
10
11If the ``is_public`` field is set to ``False`` and the comment is
12older than a specified threshold (see below), it will be considered
13spam and will be deleted.
14
15**Arguments:**
16
17``-a``, ``--age=AGE``
18    The age threshold, in days, past which a non-public comment will
19    be considered spam, and thus deleted. Defaults to 14 if not
20    supplied (and thus will delete non-public comments which are at
21    least two weeks old).
22
23``-d``, ``--dry-run``
24    Does not delete any comments, but merely prints the number of
25    comments which would have been deleted.
26
27``-s``, ``--settings=SETTINGS``
28    Django settings module to use. This argument is required.
29
30``-t``, ``--type=TYPE``
31    The type of comment to perform deletion on; ``free`` will use the
32    ``FreeComment`` model, and ``registered`` will use the ``Comment``
33    model. Defaults to ``free`` if not specified.
34
35``-v``, ``--verbose``
36    Run verbosely, printing information to standard output about each
37    comment as it is deleted.
38
39Regardless of the ``verbose``flag, this script will print the total
40number of deleted comments to standard output when finished.
41
42This script is intended to be run as a cron job; for example, to have
43it run at midnight each Sunday, with default values::
44
45    0 0 * sun python /path/to/comment_utils/bin/delete_spam_comments.py --settings=yoursite.settings
46
47"""
48
49import datetime, os
50from optparse import OptionParser
51
52
53def delete_spam_comments(age, dry_run, type, verbose):
54    from django.contrib.comments import models
55    comment_model = { 'free': models.FreeComment,
56                      'registered': models.Comment }[type]
57    age_cutoff = datetime.datetime.now() - datetime.timedelta(days=age)
58    comments_to_delete = comment_model.objects.filter(is_public__exact=False,
59                                                      submit_date__lt=age_cutoff)
60    deleted_count = comments_to_delete.count()
61    if not dry_run:
62        for comment in comments_to_delete:
63            if verbose:
64                print "Deleting spam comment '%s' on '%s', from %s" % (comment,
65                                                                       comment.get_content_object(),
66                                                                       comment.submit_date.strftime("%Y-%m-%d"))
67            comment.delete()
68    print "Deleted %s spam comments" % deleted_count
69
70
71if __name__ == '__main__':
72    usage = "usage: %prog --settings=settings [options]"
73    parser = OptionParser(usage)
74    parser.add_option('-a', '--age', dest='age', metavar='AGE', type='int',
75                      help="The age threshold, in days, past which a non-public comment will be considered spam, and thus be deleted. Defaults to 14 if not supplied.")
76    parser.add_option('-d', '--dry-run', action="store_true", dest="dry_run",
77                      help="Does not delete any comments, but merely outputs the number of comments which would have been deleted.")
78    parser.add_option('-s', '--settings', dest='settings', metavar='SETTINGS',
79                      help="Django settings module to use. This argument is required.")
80    parser.add_option('-t', '--type', dest='type', metavar='TYPE', type='choice', choices=('free', 'registered'),
81                      help="The type of comment to perform deletion on; 'free' will use the 'FreeComment' model, and 'registered' will use the 'Comment' model. Defaults to 'free' if not specified.")
82    parser.add_option('-v', '--verbose', dest='verbose', metavar='VERBOSE', action='store_true',
83                      help="Run verbosely, printing information to standard output about each comment as it is deleted.")
84    (options, args) = parser.parse_args()
85    if not options.settings:
86        parser.error("You must specify a settings module.")
87    os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
88    age = options.age or 14
89    dry_run = options.dry_run or False
90    comment_type = options.type or 'free'
91    verbose = options.verbose or False
92    delete_spam_comments(age=age, dry_run=dry_run,
93                         type=comment_type, verbose=verbose)