desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return a line number of the given object\'s docstring. Note: this method assumes that the object has a docstring.'
def _find_lineno(self, obj, source_lines):
lineno = None if inspect.ismodule(obj): lineno = 0 if inspect.isclass(obj): if (source_lines is None): return None pat = re.compile(('^\\s*class\\s*%s\\b' % getattr(obj, '__name__', '-'))) for (i, line) in enumerate(source_lines): if pat.match(line): ...
'Create a new test runner. Optional keyword arg `checker` is the `OutputChecker` that should be used to compare the expected outputs and actual outputs of doctest examples. Optional keyword arg \'verbose\' prints lots of stuff if true, only failures if false; by default, it\'s true iff \'-v\' is in sys.argv. Optional a...
def __init__(self, checker=None, verbose=None, optionflags=0):
self._checker = (checker or OutputChecker()) if (verbose is None): verbose = ('-v' in sys.argv) self._verbose = verbose self.optionflags = optionflags self.original_optionflags = optionflags self.tries = 0 self.failures = 0 self._name2ft = {} self._fakeout = _SpoofOut()
'Report that the test runner is about to process the given example. (Only displays a message if verbose=True)'
def report_start(self, out, test, example):
if self._verbose: if example.want: out(((('Trying:\n' + _indent(example.source)) + 'Expecting:\n') + _indent(example.want))) else: out((('Trying:\n' + _indent(example.source)) + 'Expecting nothing\n'))
'Report that the given example ran successfully. (Only displays a message if verbose=True)'
def report_success(self, out, test, example, got):
if self._verbose: out('ok\n')
'Report that the given example failed.'
def report_failure(self, out, test, example, got):
out((self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags)))
'Report that the given example raised an unexpected exception.'
def report_unexpected_exception(self, out, test, example, exc_info):
out(((self._failure_header(test, example) + 'Exception raised:\n') + _indent(_exception_traceback(exc_info))))
'Run the examples in `test`. Write the outcome of each example with one of the `DocTestRunner.report_*` methods, using the writer function `out`. `compileflags` is the set of compiler flags that should be used to execute examples. Return a tuple `(f, t)`, where `t` is the number of examples tried, and `f` is the num...
def __run(self, test, compileflags, out):
failures = tries = 0 original_optionflags = self.optionflags (SUCCESS, FAILURE, BOOM) = range(3) check = self._checker.check_output for (examplenum, example) in enumerate(test.examples): quiet = ((self.optionflags & REPORT_ONLY_FIRST_FAILURE) and (failures > 0)) self.optionflags = or...
'Record the fact that the given DocTest (`test`) generated `f` failures out of `t` tried examples.'
def __record_outcome(self, test, f, t):
(f2, t2) = self._name2ft.get(test.name, (0, 0)) self._name2ft[test.name] = ((f + f2), (t + t2)) self.failures += f self.tries += t
'Run the examples in `test`, and display the results using the writer function `out`. The examples are run in the namespace `test.globs`. If `clear_globs` is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after t...
def run(self, test, compileflags=None, out=None, clear_globs=True):
self.test = test if (compileflags is None): compileflags = _extract_future_flags(test.globs) save_stdout = sys.stdout if (out is None): out = save_stdout.write sys.stdout = self._fakeout save_set_trace = pdb.set_trace self.debugger = _OutputRedirectingPdb(save_stdout) sel...
'Print a summary of all the test cases that have been run by this DocTestRunner, and return a tuple `(f, t)`, where `f` is the total number of failed examples, and `t` is the total number of tried examples. The optional `verbose` argument controls how detailed the summary is. If the verbosity is not specified, then th...
def summarize(self, verbose=None):
if (verbose is None): verbose = self._verbose notests = [] passed = [] failed = [] totalt = totalf = 0 for x in self._name2ft.items(): (name, (f, t)) = x assert (f <= t) totalt += t totalf += f if (t == 0): notests.append(name) ...
'Return True iff the actual output from an example (`got`) matches the expected output (`want`). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See the documentation for `TestRunner` for ...
def check_output(self, want, got, optionflags):
if (got == want): return True if (not (optionflags & DONT_ACCEPT_TRUE_FOR_1)): if ((got, want) == ('True\n', '1\n')): return True if ((got, want) == ('False\n', '0\n')): return True if (not (optionflags & DONT_ACCEPT_BLANKLINE)): want = re.sub(('(?m)^%...
'Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`.'
def output_difference(self, example, got, optionflags):
want = example.want if (not (optionflags & DONT_ACCEPT_BLANKLINE)): got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got) if self._do_a_fancy_diff(want, got, optionflags): want_lines = want.splitlines(True) got_lines = got.splitlines(True) if (optionflags & REPORT_UDIFF):...
'Run the test case without results and without catching exceptions The unit test framework includes a debug method on test cases and test suites to support post-mortem debugging. The test code is run in such a way that errors are not caught. This way a caller can catch the errors and initiate post-mortem debugging. T...
def debug(self):
self.setUp() runner = DebugRunner(optionflags=self._dt_optionflags, checker=self._dt_checker, verbose=False) runner.run(self._dt_test) self.tearDown()
'val -> _TestClass object with associated value val. >>> t = _TestClass(123) >>> print t.get() 123'
def __init__(self, val):
self.val = val
'square() -> square TestClass\'s associated value >>> _TestClass(13).square().get() 169'
def square(self):
self.val = (self.val ** 2) return self
'get() -> return TestClass\'s associated value. >>> x = _TestClass(-42) >>> print x.get() -42'
def get(self):
return self.val
'Runs the test suite after registering a custom signal handler that triggers a graceful exit when Ctrl-C is pressed.'
def run(self, *args, **kwargs):
self._default_keyboard_interrupt_handler = signal.signal(signal.SIGINT, self._keyboard_interrupt_handler) try: result = super(DjangoTestRunner, self).run(*args, **kwargs) finally: signal.signal(signal.SIGINT, self._default_keyboard_interrupt_handler) return result
'Handles Ctrl-C by setting a flag that will stop the test run when the currently running test completes.'
def _keyboard_interrupt_handler(self, signal_number, stack_frame):
self._keyboard_interrupt_intercepted = True sys.stderr.write(' <Test run halted by Ctrl-C> ') signal.signal(signal.SIGINT, self._default_keyboard_interrupt_handler)
'Run the unit tests for all the test labels in the provided list. Labels must be of the form: - app.TestClass.test_method Run a single specific test method - app.TestClass Run all the test methods in a given class - app Search for doctests and unittests in the named application. When looking for tests, the test runner ...
def run_tests(self, test_labels, extra_tests=None, **kwargs):
self.setup_test_environment() suite = self.build_suite(test_labels, extra_tests) old_config = self.setup_databases() result = self.run_suite(suite) self.teardown_databases(old_config) self.teardown_test_environment() return self.suite_result(suite, result)
'Display stage -- can be called many times'
def render(self, context):
context.render_context.push() try: return self._render(context) finally: context.render_context.pop()
'Return a list of tokens from a given template_string.'
def tokenize(self):
in_tag = False result = [] for bit in tag_re.split(self.template_string): if bit: result.append(self.create_token(bit, in_tag)) in_tag = (not in_tag) return result
'Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string.'
def create_token(self, token_string, in_tag):
if in_tag: if token_string.startswith(VARIABLE_TAG_START): token = Token(TOKEN_VAR, token_string[len(VARIABLE_TAG_START):(- len(VARIABLE_TAG_END))].strip()) elif token_string.startswith(BLOCK_TAG_START): token = Token(TOKEN_BLOCK, token_string[len(BLOCK_TAG_START):(- len(BLOC...
'Convenient wrapper for FilterExpression'
def compile_filter(self, token):
return FilterExpression(token, self)
'Overload this method to do the actual parsing and return the result.'
def top(self):
raise NotImplementedError()
'Returns True if there is more stuff in the tag.'
def more(self):
return (self.pointer < len(self.subject))
'Undoes the last microparser. Use this for lookahead and backtracking.'
def back(self):
if (not len(self.backout)): raise TemplateSyntaxError('back called without some previous parsing') self.pointer = self.backout.pop()
'A microparser that just returns the next tag from the line.'
def tag(self):
subject = self.subject i = self.pointer if (i >= len(subject)): raise TemplateSyntaxError(('expected another tag, found end of string: %s' % subject)) p = i while ((i < len(subject)) and (subject[i] not in (' ', ' DCTB '))): i += 1 s = subject[p:i] whi...
'A microparser that parses for a value: some string constant or variable name.'
def value(self):
subject = self.subject i = self.pointer def next_space_index(subject, i): 'Increment pointer until a real space (i.e. a space not within quotes) is encountered' while ((i < len(subject)) and (subject[i] not in (' ', ' DCTB '))): if (subje...
'Resolve this variable against a given context.'
def resolve(self, context):
if (self.lookups is not None): value = self._resolve_lookup(context) else: value = self.literal if self.translate: return ugettext_lazy(value) return value
'Performs resolution of a real variable (i.e. not a literal) against the given context. As indicated by the method\'s name, this method is an implementation detail and shouldn\'t be called by external code. Use Variable.resolve() instead.'
def _resolve_lookup(self, context):
current = context for bit in self.lookups: try: current = current[bit] except (TypeError, AttributeError, KeyError): try: current = getattr(current, bit) if callable(current): if getattr(current, 'alters_data', False): ...
'Return the node rendered as a string'
def render(self, context):
pass
'Return a list of all nodes (within this node and its nodelist) of the given type'
def get_nodes_by_type(self, nodetype):
nodes = [] if isinstance(self, nodetype): nodes.append(self) for attr in self.child_nodelists: nodelist = getattr(self, attr, None) if nodelist: nodes.extend(nodelist.get_nodes_by_type(nodetype)) return nodes
'Return a list of all nodes of the given type'
def get_nodes_by_type(self, nodetype):
nodes = [] for node in self: nodes.extend(node.get_nodes_by_type(nodetype)) return nodes
'Returns a tuple containing the source and origin for the given template name.'
def load_template_source(self, template_name, template_dirs=None):
raise NotImplementedError
'Resets any state maintained by the loader instance (e.g., cached templates or cached loader modules).'
def reset(self):
pass
'Empty the template cache.'
def reset(self):
self.template_cache.clear()
'Loads templates from Python eggs via pkg_resource.resource_string. For every installed app, it tries to get the resource (app, template_name).'
def load_template_source(self, template_name, template_dirs=None):
if (resource_string is not None): pkg_name = ('templates/' + template_name) for app in settings.INSTALLED_APPS: try: return (resource_string(app, pkg_name).decode(settings.FILE_CHARSET), ('egg:%s:%s' % (app, pkg_name))) except: pass raise T...
'Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don\'t lie inside one of the template dirs are excluded from the result set, for security reasons.'
def get_template_sources(self, template_name, template_dirs=None):
if (not template_dirs): template_dirs = settings.TEMPLATE_DIRS for template_dir in template_dirs: try: (yield safe_join(template_dir, template_name)) except UnicodeDecodeError: raise except ValueError: pass
'Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don\'t lie inside one of the template dirs are excluded from the result set, for security reasons.'
def get_template_sources(self, template_name, template_dirs=None):
if (not template_dirs): template_dirs = app_template_dirs for template_dir in template_dirs: try: (yield safe_join(template_dir, template_name)) except UnicodeDecodeError: raise except ValueError: pass
'Returns what to display in error messages for this node'
def display(self):
return self.id
'Set a variable in the current context'
def __setitem__(self, key, value):
self.dicts[(-1)][key] = value
'Get a variable\'s value, starting at the current context and going upward'
def __getitem__(self, key):
for d in reversed(self.dicts): if (key in d): return d[key] raise KeyError(key)
'Delete a variable from the current context'
def __delitem__(self, key):
del self.dicts[(-1)][key]
'Like dict.update(). Pushes an entire dictionary\'s keys and values onto the context.'
def update(self, other_dict):
if (not hasattr(other_dict, '__getitem__')): raise TypeError('other_dict must be a mapping (dictionary-like) object.') self.dicts.append(other_dict) return other_dict
'Return a list of tokens from a given template_string'
def tokenize(self):
(result, upto) = ([], 0) for match in tag_re.finditer(self.template_string): (start, end) = match.span() if (start > upto): result.append(self.create_token(self.template_string[upto:start], (upto, start), False)) upto = start result.append(self.create_token(self.t...
'A flatpage can be served through a view, even when the middleware is in use'
def test_view_flatpage(self):
response = self.client.get('/flatpage_root/flatpage/') self.assertEquals(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>")
'A non-existent flatpage raises 404 when served through a view, even when the middleware is in use'
def test_view_non_existent_flatpage(self):
response = self.client.get('/flatpage_root/no_such_flatpage/') self.assertEquals(response.status_code, 404)
'A flatpage served through a view can require authentication'
def test_view_authenticated_flatpage(self):
response = self.client.get('/flatpage_root/sekrit/') self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/')
'A flatpage can be served by the fallback middlware'
def test_fallback_flatpage(self):
response = self.client.get('/flatpage/') self.assertEquals(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>")
'A non-existent flatpage raises a 404 when served by the fallback middlware'
def test_fallback_non_existent_flatpage(self):
response = self.client.get('/no_such_flatpage/') self.assertEquals(response.status_code, 404)
'POSTing to a flatpage served through a view will raise a CSRF error if no token is provided (Refs #14156)'
def test_post_view_flatpage(self):
response = self.client.post('/flatpage_root/flatpage/') self.assertEquals(response.status_code, 403)
'POSTing to a flatpage served by the middleware will raise a CSRF error if no token is provided (Refs #14156)'
def test_post_fallback_flatpage(self):
response = self.client.post('/flatpage/') self.assertEquals(response.status_code, 403)
'POSTing to an unknown page isn\'t caught as a 403 CSRF error'
def test_post_unknown_page(self):
response = self.client.post('/no_such_page/') self.assertEquals(response.status_code, 404)
'A flatpage can be served through a view'
def test_view_flatpage(self):
response = self.client.get('/flatpage_root/flatpage/') self.assertEquals(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>")
'A non-existent flatpage raises 404 when served through a view'
def test_view_non_existent_flatpage(self):
response = self.client.get('/flatpage_root/no_such_flatpage/') self.assertEquals(response.status_code, 404)
'A flatpage served through a view can require authentication'
def test_view_authenticated_flatpage(self):
response = self.client.get('/flatpage_root/sekrit/') self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/')
'A fallback flatpage won\'t be served if the middleware is disabled'
def test_fallback_flatpage(self):
response = self.client.get('/flatpage/') self.assertEquals(response.status_code, 404)
'A non-existent flatpage won\'t be served if the fallback middlware is disabled'
def test_fallback_non_existent_flatpage(self):
response = self.client.get('/no_such_flatpage/') self.assertEquals(response.status_code, 404)
'A flatpage can be served through a view, even when the middleware is in use'
def test_view_flatpage(self):
response = self.client.get('/flatpage_root/flatpage/') self.assertEquals(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>")
'A non-existent flatpage raises 404 when served through a view, even when the middleware is in use'
def test_view_non_existent_flatpage(self):
response = self.client.get('/flatpage_root/no_such_flatpage/') self.assertEquals(response.status_code, 404)
'A flatpage served through a view can require authentication'
def test_view_authenticated_flatpage(self):
response = self.client.get('/flatpage_root/sekrit/') self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/')
'A flatpage can be served by the fallback middlware'
def test_fallback_flatpage(self):
response = self.client.get('/flatpage/') self.assertEquals(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>")
'A non-existent flatpage raises a 404 when served by the fallback middlware'
def test_fallback_non_existent_flatpage(self):
response = self.client.get('/no_such_flatpage/') self.assertEquals(response.status_code, 404)
'A flatpage served by the middleware can require authentication'
def test_fallback_authenticated_flatpage(self):
response = self.client.get('/sekrit/') self.assertRedirects(response, '/accounts/login/?next=/sekrit/')
'Returns a feedgenerator.DefaultFeed object, fully populated, for this feed. Raises FeedDoesNotExist for invalid parameters.'
def get_feed(self, url=None):
if url: bits = url.split('/') else: bits = [] try: obj = self.get_object(bits) except ObjectDoesNotExist: raise FeedDoesNotExist return super(Feed, self).get_feed(obj, self.request)
'Returns an extra keyword arguments dictionary that is used when initializing the feed generator.'
def feed_extra_kwargs(self, obj):
return {}
'Returns an extra keyword arguments dictionary that is used with the `add_item` call of the feed generator.'
def item_extra_kwargs(self, item):
return {}
'Returns a feedgenerator.DefaultFeed object, fully populated, for this feed. Raises FeedDoesNotExist for invalid parameters.'
def get_feed(self, obj, request):
current_site = get_current_site(request) link = self.__get_dynamic_attr('link', obj) link = add_domain(current_site.domain, link, request.is_secure()) feed = self.feed_type(title=self.__get_dynamic_attr('title', obj), subtitle=self.__get_dynamic_attr('subtitle', obj), link=link, description=self.__get_d...
'Class method to parse get_comment_list/count/form and return a Node.'
def handle_token(cls, parser, token):
tokens = token.contents.split() if (tokens[1] != 'for'): raise template.TemplateSyntaxError(("Second argument in %r tag must be 'for'" % tokens[0])) if (len(tokens) == 5): if (tokens[3] != 'as'): raise template.TemplateSyntaxError(("Third argument in ...
'Subclasses should override this.'
def get_context_value_from_queryset(self, context, qs):
raise NotImplementedError
'Class method to parse render_comment_form and return a Node.'
def handle_token(cls, parser, token):
tokens = token.contents.split() if (tokens[1] != 'for'): raise template.TemplateSyntaxError(("Second argument in %r tag must be 'for'" % tokens[0])) if (len(tokens) == 3): return cls(object_expr=parser.compile_filter(tokens[2])) elif (len(tokens) == 4): retur...
'Class method to parse render_comment_list and return a Node.'
def handle_token(cls, parser, token):
tokens = token.contents.split() if (tokens[1] != 'for'): raise template.TemplateSyntaxError(("Second argument in %r tag must be 'for'" % tokens[0])) if (len(tokens) == 3): return cls(object_expr=parser.compile_filter(tokens[2])) elif (len(tokens) == 4): retur...
'Get a URL suitable for redirecting to the content object.'
def get_content_object_url(self):
return urlresolvers.reverse('comments-url-redirect', args=(self.content_type_id, self.object_pk))
'Get a dictionary that pulls together information about the poster safely for both authenticated and non-authenticated comments. This dict will have ``name``, ``email``, and ``url`` fields.'
def _get_userinfo(self):
if (not hasattr(self, '_userinfo')): self._userinfo = {'name': self.user_name, 'email': self.user_email, 'url': self.user_url} if self.user_id: u = self.user if u.email: self._userinfo['email'] = u.email if u.get_full_name(): self._...
'Return this comment as plain text. Useful for emails.'
def get_as_text(self):
d = {'user': (self.user or self.name), 'date': self.submit_date, 'comment': self.comment, 'domain': self.site.domain, 'url': self.get_absolute_url()} return (_('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % d)
'QuerySet for all comments currently in the moderation queue.'
def in_moderation(self):
return self.get_query_set().filter(is_public=False, is_removed=False)
'QuerySet for all comments for a particular model (either an instance or a class).'
def for_model(self, model):
ct = ContentType.objects.get_for_model(model) qs = self.get_query_set().filter(content_type=ct) if isinstance(model, models.Model): qs = qs.filter(object_pk=force_unicode(model._get_pk_val())) return qs
'Flag, approve, or remove some comments from an admin action. Actually calls the `action` argument to perform the heavy lifting.'
def _bulk_flag(self, request, queryset, action, done_message):
n_comments = 0 for comment in queryset: action(request, comment) n_comments += 1 msg = ungettext(u'1 comment was successfully %(action)s.', u'%(count)s comments were successfully %(action)s.', n_comments) self.message_user(request, (msg % {'count': n_comments, 'ac...
'Return just those errors associated with security'
def security_errors(self):
errors = ErrorDict() for f in ['honeypot', 'timestamp', 'security_hash']: if (f in self.errors): errors[f] = self.errors[f] return errors
'Check the security hash.'
def clean_security_hash(self):
security_hash_dict = {'content_type': self.data.get('content_type', ''), 'object_pk': self.data.get('object_pk', ''), 'timestamp': self.data.get('timestamp', '')} expected_hash = self.generate_security_hash(**security_hash_dict) actual_hash = self.cleaned_data['security_hash'] if (expected_hash != actua...
'Make sure the timestamp isn\'t too far (> 2 hours) in the past.'
def clean_timestamp(self):
ts = self.cleaned_data['timestamp'] if ((time.time() - ts) > ((2 * 60) * 60)): raise forms.ValidationError('Timestamp check failed') return ts
'Generate a dict of security data for "initial" data.'
def generate_security_data(self):
timestamp = int(time.time()) security_dict = {'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_val()), 'timestamp': str(timestamp), 'security_hash': self.initial_security_hash(timestamp)} return security_dict
'Generate the initial security hash from self.content_object and a (unix) timestamp.'
def initial_security_hash(self, timestamp):
initial_security_dict = {'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_val()), 'timestamp': str(timestamp)} return self.generate_security_hash(**initial_security_dict)
'Generate a (SHA1) security hash from the provided info.'
def generate_security_hash(self, content_type, object_pk, timestamp):
info = (content_type, object_pk, timestamp, settings.SECRET_KEY) return sha_constructor(''.join(info)).hexdigest()
'Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user`` or ``ip_address``).'
def get_comment_object(self):
if (not self.is_valid()): raise ValueError('get_comment_object may only be called on valid forms') CommentModel = self.get_comment_model() new = CommentModel(**self.get_comment_create_data()) new = self.check_for_duplicate_comment(new) return new
'Get the comment model to create with this form. Subclasses in custom comment apps should override this, get_comment_create_data, and perhaps check_for_duplicate_comment to provide custom comment models.'
def get_comment_model(self):
return Comment
'Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model can override this method to add extra fields onto a custom comment model.'
def get_comment_create_data(self):
return dict(content_type=ContentType.objects.get_for_model(self.target_object), object_pk=force_unicode(self.target_object._get_pk_val()), user_name=self.cleaned_data['name'], user_email=self.cleaned_data['email'], user_url=self.cleaned_data['url'], comment=self.cleaned_data['comment'], submit_date=datetime.datetim...
'Check that a submitted comment isn\'t a duplicate. This might be caused by someone posting a comment twice. If it is a dup, silently return the *previous* comment.'
def check_for_duplicate_comment(self, new):
possible_duplicates = self.get_comment_model()._default_manager.using(self.target_object._state.db).filter(content_type=new.content_type, object_pk=new.object_pk, user_name=new.user_name, user_email=new.user_email, user_url=new.user_url) for old in possible_duplicates: if ((old.submit_date.date() == new...
'If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn\'t contain anything in PROFANITIES_LIST.'
def clean_comment(self):
comment = self.cleaned_data['comment'] if (settings.COMMENTS_ALLOW_PROFANITIES == False): bad_words = [w for w in settings.PROFANITIES_LIST if (w in comment.lower())] if bad_words: plural = (len(bad_words) > 1) raise forms.ValidationError((ungettext('Watch your mout...
'Check that nothing\'s been entered into the honeypot.'
def clean_honeypot(self):
value = self.cleaned_data['honeypot'] if value: raise forms.ValidationError(self.fields['honeypot'].label) return value
'Internal helper which will return a ``datetime.timedelta`` representing the time between ``now`` and ``then``. Assumes ``now`` is a ``datetime.date`` or ``datetime.datetime`` later than ``then``. If ``now`` and ``then`` are not of the same type due to one of them being a ``datetime.date`` and the other being a ``datet...
def _get_delta(self, now, then):
if (now.__class__ is not then.__class__): now = datetime.date(now.year, now.month, now.day) then = datetime.date(then.year, then.month, then.day) if (now < then): raise ValueError('Cannot determine moderation rules because date field is set to a value ...
'Determine whether a given comment is allowed to be posted on a given object. Return ``True`` if the comment should be allowed, ``False otherwise.'
def allow(self, comment, content_object, request):
if self.enable_field: if (not getattr(content_object, self.enable_field)): return False if (self.auto_close_field and self.close_after): if (self._get_delta(datetime.datetime.now(), getattr(content_object, self.auto_close_field)).days >= self.close_after): return False ...
'Determine whether a given comment on a given object should be allowed to show up immediately, or should be marked non-public and await approval. Return ``True`` if the comment should be moderated (marked non-public), ``False`` otherwise.'
def moderate(self, comment, content_object, request):
if (self.auto_moderate_field and self.moderate_after): if (self._get_delta(datetime.datetime.now(), getattr(content_object, self.auto_moderate_field)).days >= self.moderate_after): return True return False
'Send email notification of a new comment to site staff when email notifications have been requested.'
def email(self, comment, content_object, request):
if (not self.email_notification): return recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS] t = loader.get_template('comments/comment_notification_email.txt') c = Context({'comment': comment, 'content_object': content_object}) subject = ('[%s] New comment pos...
'Hook up the moderation methods to pre- and post-save signals from the comment models.'
def connect(self):
signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=comments.get_model()) signals.comment_was_posted.connect(self.post_save_moderation, sender=comments.get_model())
'Register a model or a list of models for comment moderation, using a particular moderation class. Raise ``AlreadyModerated`` if any of the models are already registered.'
def register(self, model_or_iterable, moderation_class):
if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if (model in self._registry): raise AlreadyModerated(("The model '%s' is already being moderated" % model._meta.module_name)) self._registry[...
'Remove a model or a list of models from the list of models whose comments will be moderated. Raise ``NotModerated`` if any of the models are not currently registered for moderation.'
def unregister(self, model_or_iterable):
if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if (model not in self._registry): raise NotModerated(("The model '%s' is not currently being moderated" % model._meta.module_name)) del se...
'Apply any necessary pre-save moderation steps to new comments.'
def pre_save_moderation(self, sender, comment, request, **kwargs):
model = comment.content_type.model_class() if (model not in self._registry): return content_object = comment.content_object moderation_class = self._registry[model] if (not moderation_class.allow(comment, content_object, request)): return False if moderation_class.moderate(commen...
'Apply any necessary post-save moderation steps to new comments.'
def post_save_moderation(self, sender, comment, request, **kwargs):
model = comment.content_type.model_class() if (model not in self._registry): return self._registry[model].email(comment, comment.content_object, request)
'Returns the ModelDatabrowse class for this model.'
def model_databrowse(self):
return self.site.registry[self.model]