desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Renders the template for the given step, returning an HttpResponse object. Override this method if you want to add a custom context, return a different MIME type, etc. If you only need to override the template name, use get_template() instead. The template will be rendered with the following context: step_field -- The...
def render_template(self, request, form, previous_fields, step, context=None):
context = (context or {}) context.update(self.extra_context) return render_to_response(self.get_template(step), dict(context, step_field=self.step_field_name, step0=step, step=(step + 1), step_count=self.num_steps(), form=form, previous_fields=previous_fields), context_instance=RequestContext(request))
'Hook for modifying the FormWizard\'s internal state, given a fully validated Form object. The Form is guaranteed to have clean, valid data. This method should *not* modify any of that data. Rather, it might want to set self.extra_context or dynamically alter self.form_list, based on previously submitted forms. Note th...
def process_step(self, request, form, step):
pass
'Hook for doing something with the validated data. This is responsible for the final processing. form_list is a list of Form instances, each containing clean, valid data.'
def done(self, request, form_list):
raise NotImplementedError(('Your %s class has not defined a done() method, which is required.' % self.__class__.__name__))
'Given a first-choice name, adds an underscore to the name until it reaches a name that isn\'t claimed by any field in the form. This is calculated rather than being hard-coded so that no field names are off-limits for use in the form.'
def unused_name(self, name):
while 1: try: f = self.form.base_fields[name] except KeyError: break name += '_' return name
'Displays the form'
def preview_get(self, request):
f = self.form(auto_id=AUTO_ID) return render_to_response(self.form_template, {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state}, context_instance=RequestContext(request))
'Validates the POST data. If valid, displays the preview page. Else, redisplays form.'
def preview_post(self, request):
f = self.form(request.POST, auto_id=AUTO_ID) context = {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state} if f.is_valid(): self.process_preview(request, f, context) context['hash_field'] = self.unused_name('hash') context['hash_value'] = self.security_hash(req...
'Validates the POST data. If valid, calls done(). Else, redisplays form.'
def post_post(self, request):
f = self.form(request.POST, auto_id=AUTO_ID) if f.is_valid(): if (self.security_hash(request, f) != request.POST.get(self.unused_name('hash'))): return self.failed_hash(request) return self.done(request, f.cleaned_data) else: return render_to_response(self.form_template, ...
'Given captured args and kwargs from the URLconf, saves something in self.state and/or raises Http404 if necessary. For example, this URLconf captures a user_id variable: (r\'^contact/(?P<user_id>\d{1,6})/$\', MyFormPreview(MyForm)), In this case, the kwargs variable in parse_params would be {\'user_id\': 32} for a req...
def parse_params(self, *args, **kwargs):
pass
'Given a validated form, performs any extra processing before displaying the preview page, and saves any extra data in context.'
def process_preview(self, request, form, context):
pass
'Calculates the security hash for the given HttpRequest and Form instances. Subclasses may want to take into account request-specific information, such as the IP address.'
def security_hash(self, request, form):
return security_hash(request, form)
'Returns an HttpResponse in the case of an invalid security hash.'
def failed_hash(self, request):
return self.preview_post(request)
'Does something with the cleaned_data and returns an HttpResponseRedirect.'
def done(self, request, cleaned_data):
raise NotImplementedError(('You must define a done() method on your %s subclass.' % self.__class__.__name__))
'Verifies name mangling to get uniue field name.'
def test_unused_name(self):
self.assertEqual(self.preview.unused_name('field1'), 'field1__')
'Test contrib.formtools.preview form retrieval. Use the client library to see if we can sucessfully retrieve the form (mostly testing the setup ROOT_URLCONF process). Verify that an additional hidden input field is created to manage the stage.'
def test_form_get(self):
response = self.client.get('/test1/') stage = (self.input % 1) self.assertContains(response, stage, 1)
'Test contrib.formtools.preview form preview rendering. Use the client library to POST to the form to see if a preview is returned. If we do get a form back check that the hidden value is correctly managing the state of the form.'
def test_form_preview(self):
self.test_data.update({'stage': 1}) response = self.client.post('/test1/', self.test_data) stage = (self.input % 2) self.assertContains(response, stage, 1)
'Test contrib.formtools.preview form submittal. Use the client library to POST to the form with stage set to 3 to see if our forms done() method is called. Check first without the security hash, verify failure, retry with security hash and verify sucess.'
def test_form_submit(self):
self.test_data.update({'stage': 2}) response = self.client.post('/test1/', self.test_data) self.failIfEqual(response.content, success_string) hash = self.preview.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash}) response = self.client.post('/test1/', self.test_d...
'Test contrib.formtools.preview form submittal when form contains: BooleanField(required=False) Ticket: #6209 - When an unchecked BooleanField is previewed, the preview form\'s hash would be computed with no value for ``bool1``. However, when the preview form is rendered, the unchecked hidden BooleanField would be rend...
def test_bool_submit(self):
self.test_data.update({'stage': 2}) hash = self.preview.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash, 'bool1': u'False'}) response = self.client.post('/test1/', self.test_data) self.assertEqual(response.content, success_string)
'Regression test for #10034: the hash generation function should ignore leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas).'
def test_textfield_hash(self):
f1 = HashTestForm({'name': 'joe', 'bio': 'Nothing notable.'}) f2 = HashTestForm({'name': ' joe', 'bio': 'Nothing notable. '}) hash1 = utils.security_hash(None, f1) hash2 = utils.security_hash(None, f2) self.assertEqual(hash1, hash2)
'Regression test for #10643: the security hash should allow forms with empty_permitted = True, or forms where data has not changed.'
def test_empty_permitted(self):
f1 = HashTestBlankForm({}) f2 = HashTestForm({}, empty_permitted=True) hash1 = utils.security_hash(None, f1) hash2 = utils.security_hash(None, f2) self.assertEqual(hash1, hash2)
'step should be zero for the first form'
def test_step_starts_at_zero(self):
wizard = WizardClass([WizardPageOneForm, WizardPageTwoForm]) request = DummyRequest() wizard(request) self.assertEquals(0, wizard.step)
'step should be incremented when we go to the next page'
def test_step_increments(self):
wizard = WizardClass([WizardPageOneForm, WizardPageTwoForm]) request = DummyRequest(POST={'0-field': 'test', 'wizard_step': '0'}) response = wizard(request) self.assertEquals(1, wizard.step)
'Regression test for ticket #14498. All previous steps\' forms should be validated.'
def test_14498(self):
that = self reached = [False] class WizardWithProcessStep(WizardClass, ): def process_step(self, request, form, step): reached[0] = True that.assertTrue(hasattr(form, 'cleaned_data')) wizard = WizardWithProcessStep([WizardPageOneForm, WizardPageTwoForm, WizardPageThreeFor...
'Regression test for ticket #14576. The form of the last step is not passed to the done method.'
def test_14576(self):
reached = [False] that = self class Wizard(WizardClass, ): def done(self, request, form_list): reached[0] = True that.assertTrue((len(form_list) == 2)) wizard = Wizard([WizardPageOneForm, WizardPageTwoForm]) data = {'0-field': 'test', '1-field': 'test2', 'hash_0': '2f...
'Regression test for ticket #15075. Allow modifying wizard\'s form_list in process_step.'
def test_15075(self):
reached = [False] that = self class WizardWithProcessStep(WizardClass, ): def process_step(self, request, form, step): if (step == 0): self.form_list[1] = WizardPageTwoAlternativeForm if (step == 1): that.assertTrue(isinstance(form, WizardPageT...
'Returns the ContentType object for a given model, creating the ContentType if necessary. Lookups are cached so that subsequent lookups for the same model don\'t hit the database.'
def get_for_model(self, model):
opts = model._meta while opts.proxy: model = opts.proxy_for_model opts = model._meta key = (opts.app_label, opts.object_name.lower()) try: ct = self.__class__._cache[self.db][key] except KeyError: (ct, created) = self.get_or_create(app_label=opts.app_label, model=opts...
'Lookup a ContentType by ID. Uses the same shared cache as get_for_model (though ContentTypes are obviously not created on-the-fly by get_by_id).'
def get_for_id(self, id):
try: ct = self.__class__._cache[self.db][id] except KeyError: ct = self.get(pk=id) self._add_to_cache(self.db, ct) return ct
'Clear out the content-type cache. This needs to happen during database flushes to prevent caching of "stale" content type IDs (see django.contrib.contenttypes.management.update_contenttypes for where this gets called).'
def clear_cache(self):
self.__class__._cache.clear()
'Insert a ContentType into the cache.'
def _add_to_cache(self, using, ct):
model = ct.model_class() key = (model._meta.app_label, model._meta.object_name.lower()) self.__class__._cache.setdefault(using, {})[key] = ct self.__class__._cache.setdefault(using, {})[ct.id] = ct
'Returns the Python model class for this type of content.'
def model_class(self):
from django.db import models return models.get_model(self.app_label, self.model)
'Returns an object of this type for the keyword arguments given. Basically, this is a proxy around this object_type\'s get_object() model method. The ObjectNotExist exception, if thrown, will not be caught, so code that calls this method should catch it.'
def get_object_for_this_type(self, **kwargs):
return self.model_class()._default_manager.using(self._state.db).get(**kwargs)
'Handles initializing an object with the generic FK instaed of content-type/object-id fields.'
def instance_pre_init(self, signal, sender, args, kwargs, **_kwargs):
if (self.name in kwargs): value = kwargs.pop(self.name) kwargs[self.ct_field] = self.get_content_type(obj=value) kwargs[self.fk_field] = value._get_pk_val()
'Return an extra filter to the queryset so that the results are filtered on the appropriate content type.'
def extra_filters(self, pieces, pos, negate):
if negate: return [] ContentType = get_model('contenttypes', 'contenttype') content_type = ContentType.objects.get_for_model(self.model) prefix = '__'.join(pieces[:(pos + 1)]) return [(('%s__%s' % (prefix, self.content_type_field_name)), content_type)]
'Make sure that the content type cache (see ContentTypeManager) works correctly. Lookups for a particular content type -- by model or by ID -- should hit the database only on the first lookup.'
def test_lookup_cache(self):
ContentType.objects.get_for_model(ContentType) self.assertEqual(1, len(db.connection.queries)) ct = ContentType.objects.get_for_model(ContentType) self.assertEqual(1, len(db.connection.queries)) ContentType.objects.get_for_id(ct.id) self.assertEqual(1, len(db.connection.queries)) ContentType...
'Check that the shortcut view (used for the admin "view on site" functionality) returns a complete URL regardless of whether the sites framework is installed'
def test_shortcut_view(self):
request = HttpRequest() request.META = {'SERVER_NAME': 'Example.com', 'SERVER_PORT': '80'} from django.contrib.auth.models import User user_ct = ContentType.objects.get_for_model(User) obj = User.objects.create(username='john') if Site._meta.installed: response = shortcut(request, user_c...
'Returns the storage backend, setting its loaded data to the ``data`` argument. This method avoids the storage ``_get`` method from getting called so that other parts of the storage backend can be tested independent of the message retrieval logic.'
def get_storage(self, data=None):
storage = self.storage_class(self.get_request()) storage._loaded_data = (data or []) return storage
'With the message middleware enabled, tests that messages are properly stored and then retrieved across the full request/redirect/response cycle.'
def test_full_request_response_cycle(self):
settings.MESSAGE_LEVEL = constants.DEBUG data = {'messages': [('Test message %d' % x) for x in xrange(10)]} show_url = reverse('django.contrib.messages.tests.urls.show') for level in ('debug', 'info', 'success', 'warning', 'error'): add_url = reverse('django.contrib.messages.tests.urls.add...
'Tests that messages persist properly when multiple POSTs are made before a GET.'
def test_multiple_posts(self):
settings.MESSAGE_LEVEL = constants.DEBUG data = {'messages': [('Test message %d' % x) for x in xrange(10)]} show_url = reverse('django.contrib.messages.tests.urls.show') messages = [] for level in ('debug', 'info', 'success', 'warning', 'error'): messages.extend([Message(self.levels[le...
'Tests that the messages API successfully falls back to using user.message_set to store messages directly when the middleware is disabled.'
def test_middleware_disabled_auth_user(self):
settings.MESSAGE_LEVEL = constants.DEBUG user = User.objects.create_user('test', 'test@example.com', 'test') self.client.login(username='test', password='test') settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) settings.INSTALLED_APPS.remove('django.contrib.messages') settings.MIDDLEWARE_C...
'Tests that, when the middleware is disabled and a user is not logged in, an exception is raised when one attempts to store a message.'
def test_middleware_disabled_anon_user(self):
settings.MESSAGE_LEVEL = constants.DEBUG settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) settings.INSTALLED_APPS.remove('django.contrib.messages') settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) settings.MIDDLEWARE_CLASSES.remove('django.contrib.messages.middleware.MessageMid...
'Tests that, when the middleware is disabled and a user is not logged in, an exception is not raised if \'fail_silently\' = True'
def test_middleware_disabled_anon_user_fail_silently(self):
settings.MESSAGE_LEVEL = constants.DEBUG settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) settings.INSTALLED_APPS.remove('django.contrib.messages') settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) settings.MIDDLEWARE_CLASSES.remove('django.contrib.messages.middleware.MessageMid...
'Returns the number of messages being stored after a ``storage.update()`` call.'
def stored_messages_count(self, storage, response):
raise NotImplementedError('This method must be set by a subclass.')
'Tests that reading the existing storage doesn\'t cause the data to be lost.'
def test_existing_read(self):
storage = self.get_existing_storage() self.assertFalse(storage.used) data = list(storage) self.assert_(storage.used) self.assertEqual(data, list(storage))
'Tests that, if the data exceeds what is allowed in a cookie, older messages are removed before saving (and returned by the ``update`` method).'
def test_max_cookie_length(self):
storage = self.get_storage() response = self.get_response() msg_size = int((((CookieStorage.max_cookie_size - 54) / 4.5) - 37)) for i in range(5): storage.add(constants.INFO, (str(i) * msg_size)) unstored_messages = storage.update(response) cookie_storing = self.stored_messages_count(sto...
'Tests that a complex nested data structure containing Message instances is properly encoded/decoded by the custom JSON encoder/decoder classes.'
def test_json_encoder_decoder(self):
messages = [{'message': Message(constants.INFO, 'Test message'), 'message_list': ([Message(constants.INFO, 'message %s') for x in xrange(5)] + [{'another-message': Message(constants.ERROR, 'error')}])}, Message(constants.INFO, 'message %s')] encoder = MessageEncoder(separators=(',', ':')) value = e...
'Return the storage totals from both cookie and session backends.'
def stored_messages_count(self, storage, response):
total = (self.stored_cookie_messages_count(storage, response) + self.stored_session_messages_count(storage, response)) return total
'Confirms that: (1) A short number of messages whose data size doesn\'t exceed what is allowed in a cookie will all be stored in the CookieBackend. (2) If the CookieBackend can store all messages, the SessionBackend won\'t be written to at all.'
def test_no_fallback(self):
storage = self.get_storage() response = self.get_response() self.get_session_storage(storage)._store = None for i in range(5): storage.add(constants.INFO, (str(i) * 100)) storage.update(response) cookie_storing = self.stored_cookie_messages_count(storage, response) self.assertEqual(c...
'Confirms that, if the data exceeds what is allowed in a cookie, messages which did not fit are stored in the SessionBackend.'
def test_session_fallback(self):
storage = self.get_storage() response = self.get_response() msg_size = int((((CookieStorage.max_cookie_size - 54) / 4.5) - 37)) for i in range(5): storage.add(constants.INFO, (str(i) * msg_size)) storage.update(response) cookie_storing = self.stored_cookie_messages_count(storage, respons...
'Confirms that large messages, none of which fit in a cookie, are stored in the SessionBackend (and nothing is stored in the CookieBackend).'
def test_session_fallback_only(self):
storage = self.get_storage() response = self.get_response() storage.add(constants.INFO, ('x' * 5000)) storage.update(response) cookie_storing = self.stored_cookie_messages_count(storage, response) self.assertEqual(cookie_storing, 0) session_storing = self.stored_session_messages_count(storag...
'Makes sure that the response middleware is tolerant of messages not existing on request.'
def test_response_without_messages(self):
request = http.HttpRequest() response = http.HttpResponse() self.middleware.process_response(request, response)
'Prepares the message for serialization by forcing the ``message`` and ``extra_tags`` to unicode in case they are lazy translations. Known "safe" types (None, int, etc.) are not converted (see Django\'s ``force_unicode`` implementation for details).'
def _prepare(self):
self.message = force_unicode(self.message, strings_only=True) self.extra_tags = force_unicode(self.extra_tags, strings_only=True)
'Returns a list of loaded messages, retrieving them first if they have not been loaded yet.'
@property def _loaded_messages(self):
if (not hasattr(self, '_loaded_data')): (messages, all_retrieved) = self._get() self._loaded_data = (messages or []) return self._loaded_data
'Retrieves a list of stored messages. Returns a tuple of the messages and a flag indicating whether or not all the messages originally intended to be stored in this storage were, in fact, stored and retrieved; e.g., ``(messages, all_retrieved)``. **This method must be implemented by a subclass.** If it is possible to t...
def _get(self, *args, **kwargs):
raise NotImplementedError()
'Stores a list of messages, returning a list of any messages which could not be stored. One type of object must be able to be stored, ``Message``. **This method must be implemented by a subclass.**'
def _store(self, messages, response, *args, **kwargs):
raise NotImplementedError()
'Prepares a list of messages for storage.'
def _prepare_messages(self, messages):
for message in messages: message._prepare()
'Stores all unread messages. If the backend has yet to be iterated, previously stored messages will be stored again. Otherwise, only messages added after the last iteration will be stored.'
def update(self, response):
self._prepare_messages(self._queued_messages) if self.used: return self._store(self._queued_messages, response) elif self.added_new: messages = (self._loaded_messages + self._queued_messages) return self._store(messages, response)
'Queues a message to be stored. The message is only queued if it contained something and its level is not less than the recording level (``self.level``).'
def add(self, level, message, extra_tags=''):
if (not message): return level = int(level) if (level < self.level): return self.added_new = True message = Message(level, message, extra_tags=extra_tags) self._queued_messages.append(message)
'Returns the minimum recorded level. The default level is the ``MESSAGE_LEVEL`` setting. If this is not found, the ``INFO`` level is used.'
def _get_level(self):
if (not hasattr(self, '_level')): self._level = getattr(settings, 'MESSAGE_LEVEL', constants.INFO) return self._level
'Sets a custom minimum recorded level. If set to ``None``, the default level will be used (see the ``_get_level`` method).'
def _set_level(self, value=None):
if ((value is None) and hasattr(self, '_level')): del self._level else: self._level = int(value)
'Retrieves a list of messages from the messages cookie. If the not_finished sentinel value is found at the end of the message list, remove it and return a result indicating that not all messages were retrieved by this storage.'
def _get(self, *args, **kwargs):
data = self.request.COOKIES.get(self.cookie_name) messages = self._decode(data) all_retrieved = (not (messages and (messages[(-1)] == self.not_finished))) if (messages and (not all_retrieved)): messages.pop() return (messages, all_retrieved)
'Either sets the cookie with the encoded data if there is any data to store, or deletes the cookie.'
def _update_cookie(self, encoded_data, response):
if encoded_data: response.set_cookie(self.cookie_name, encoded_data) else: response.delete_cookie(self.cookie_name)
'Stores the messages to a cookie, returning a list of any messages which could not be stored. If the encoded data is larger than ``max_cookie_size``, removes messages until the data fits (these are the messages which are returned), and add the not_finished sentinel value to indicate as much.'
def _store(self, messages, response, remove_oldest=True, *args, **kwargs):
unstored_messages = [] encoded_data = self._encode(messages) if self.max_cookie_size: cookie = CompatCookie() def stored_length(val): return len(cookie.value_encode(val)[1]) while (encoded_data and (stored_length(encoded_data) > self.max_cookie_size)): if remo...
'Creates an HMAC/SHA1 hash based on the value and the project setting\'s SECRET_KEY, modified to make it unique for the present purpose.'
def _hash(self, value):
key = ('django.contrib.messages' + settings.SECRET_KEY) return hmac.new(key, value, sha_hmac).hexdigest()
'Returns an encoded version of the messages list which can be stored as plain text. Since the data will be retrieved from the client-side, the encoded data also contains a hash to ensure that the data was not tampered with.'
def _encode(self, messages, encode_empty=False):
if (messages or encode_empty): encoder = MessageEncoder(separators=(',', ':')) value = encoder.encode(messages) return ('%s$%s' % (self._hash(value), value))
'Safely decodes a encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, ``None`` is returned.'
def _decode(self, data):
if (not data): return None bits = data.split('$', 1) if (len(bits) == 2): (hash, value) = bits if (hash == self._hash(value)): try: return json.loads(value, cls=MessageDecoder) except ValueError: pass self.used = True re...
'Returns the QuerySet containing all user messages (or ``None`` if request.user is not a contrib.auth User).'
def _get_messages_queryset(self):
user = getattr(self.request, 'user', None) if isinstance(user, User): return user._message_set.all()
'Retrieves a list of messages assigned to the User. This backend never stores anything, so all_retrieved is assumed to be False.'
def _get(self, *args, **kwargs):
queryset = self._get_messages_queryset() if (queryset is None): return ([], False) messages = [] for user_message in queryset: messages.append(Message(constants.INFO, user_message.message)) return (messages, False)
'Removes any messages assigned to the User and returns the list of messages (since no messages are stored in this read-only storage).'
def _store(self, messages, *args, **kwargs):
queryset = self._get_messages_queryset() if (queryset is not None): queryset.delete() return messages
'Retrieves a list of messages from the request\'s session. This storage always stores everything it is given, so return True for the all_retrieved flag.'
def _get(self, *args, **kwargs):
return (self.request.session.get(self.session_key), True)
'Stores a list of messages to the request\'s session.'
def _store(self, messages, response, *args, **kwargs):
if messages: self.request.session[self.session_key] = messages else: self.request.session.pop(self.session_key, None) return []
'Gets a single list of messages from all storage backends.'
def _get(self, *args, **kwargs):
all_messages = [] for storage in self.storages: (messages, all_retrieved) = storage._get() if (messages is None): break if messages: self._used_storages.add(storage) all_messages.extend(messages) if all_retrieved: break return (all_...
'Stores the messages, returning any unstored messages after trying all backends. For each storage backend, any messages not stored are passed on to the next backend.'
def _store(self, messages, response, *args, **kwargs):
for storage in self.storages: if messages: messages = storage._store(messages, response, remove_oldest=False) elif (storage in self._used_storages): storage._store([], response) self._used_storages.remove(storage) return messages
'Updates the storage backend (i.e., saves the messages). If not all messages could not be stored and ``DEBUG`` is ``True``, a ``ValueError`` is raised.'
def process_response(self, request, response):
if hasattr(request, '_messages'): unstored_messages = request._messages.update(response) if (unstored_messages and settings.DEBUG): raise ValueError('Not all temporary messages could be stored.') return response
'Adds an item to the feed. All args are expected to be Python Unicode objects except pubdate, which is a datetime.datetime object, and enclosure, which is an instance of the Enclosure class.'
def add_item(self, title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, enclosure=None, categories=(), item_copyright=None, ttl=None, **kwargs):
to_unicode = (lambda s: force_unicode(s, strings_only=True)) if categories: categories = [to_unicode(c) for c in categories] if (ttl is not None): ttl = force_unicode(ttl) item = {'title': to_unicode(title), 'link': iri_to_uri(link), 'description': to_unicode(description), 'author_email'...
'Return extra attributes to place on the root (i.e. feed/channel) element. Called from write().'
def root_attributes(self):
return {}
'Add elements in the root (i.e. feed/channel) element. Called from write().'
def add_root_elements(self, handler):
pass
'Return extra attributes to place on each item (i.e. item/entry) element.'
def item_attributes(self, item):
return {}
'Add elements on each item (i.e. item/entry) element.'
def add_item_elements(self, handler, item):
pass
'Outputs the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this.'
def write(self, outfile, encoding):
raise NotImplementedError
'Returns the feed in the given encoding as a string.'
def writeString(self, encoding):
from StringIO import StringIO s = StringIO() self.write(s, encoding) return s.getvalue()
'Returns the latest item\'s pubdate. If none of them have a pubdate, this returns the current date/time.'
def latest_post_date(self):
updates = [i['pubdate'] for i in self.items if (i['pubdate'] is not None)] if (len(updates) > 0): updates.sort() return updates[(-1)] else: return datetime.datetime.now()
'All args are expected to be Python Unicode objects'
def __init__(self, url, length, mime_type):
(self.length, self.mime_type) = (length, mime_type) self.url = iri_to_uri(url)
'Concatenating a safe string with another safe string or safe unicode object is safe. Otherwise, the result is no longer safe.'
def __add__(self, rhs):
t = super(SafeString, self).__add__(rhs) if isinstance(rhs, SafeUnicode): return SafeUnicode(t) elif isinstance(rhs, SafeString): return SafeString(t) return t
'Wrap a call to a normal unicode method up so that we return safe results. The method that is being wrapped is passed in the \'method\' argument.'
def _proxy_method(self, *args, **kwargs):
method = kwargs.pop('method') data = method(self, *args, **kwargs) if isinstance(data, str): return SafeString(data) else: return SafeUnicode(data)
'Concatenating a safe unicode object with another safe string or safe unicode object is safe. Otherwise, the result is no longer safe.'
def __add__(self, rhs):
t = super(SafeUnicode, self).__add__(rhs) if isinstance(rhs, SafeData): return SafeUnicode(t) return t
'Wrap a call to a normal unicode method up so that we return safe results. The method that is being wrapped is passed in the \'method\' argument.'
def _proxy_method(self, *args, **kwargs):
method = kwargs.pop('method') data = method(self, *args, **kwargs) if isinstance(data, str): return SafeString(data) else: return SafeUnicode(data)
'Returns a copy of this object.'
def copy(self):
return self.__copy__()
'Returns the value of the item at the given zero-based index.'
def value_for_index(self, index):
return self[self.keyOrder[index]]
'Inserts the key, value pair before the item with the given index.'
def insert(self, index, key, value):
if (key in self.keyOrder): n = self.keyOrder.index(key) del self.keyOrder[n] if (n < index): index -= 1 self.keyOrder.insert(index, key) super(SortedDict, self).__setitem__(key, value)
'Returns a copy of this object.'
def copy(self):
obj = self.__class__(self) obj.keyOrder = self.keyOrder[:] return obj
'Replaces the normal dict.__repr__ with a version that returns the keys in their sorted order.'
def __repr__(self):
return ('{%s}' % ', '.join([('%r: %r' % (k, v)) for (k, v) in self.items()]))
'Returns the last data value for this key, or [] if it\'s an empty list; raises KeyError if not found.'
def __getitem__(self, key):
try: list_ = super(MultiValueDict, self).__getitem__(key) except KeyError: raise MultiValueDictKeyError(('Key %r not found in %r' % (key, self))) try: return list_[(-1)] except IndexError: return []
'Returns the last data value for the passed key. If key doesn\'t exist or value is an empty list, then default is returned.'
def get(self, key, default=None):
try: val = self[key] except KeyError: return default if (val == []): return default return val
'Returns the list of values for the passed key. If key doesn\'t exist, then an empty list is returned.'
def getlist(self, key):
try: return super(MultiValueDict, self).__getitem__(key) except KeyError: return []
'Appends an item to the internal list associated with key.'
def appendlist(self, key, value):
self.setlistdefault(key, []) super(MultiValueDict, self).__setitem__(key, (self.getlist(key) + [value]))
'Returns a list of (key, value) pairs, where value is the last item in the list associated with the key.'
def items(self):
return [(key, self[key]) for key in self.keys()]
'Yields (key, value) pairs, where value is the last item in the list associated with the key.'
def iteritems(self):
for key in self.keys(): (yield (key, self[key]))
'Returns a list of (key, list) pairs.'
def lists(self):
return super(MultiValueDict, self).items()
'Yields (key, list) pairs.'
def iterlists(self):
return super(MultiValueDict, self).iteritems()
'Returns a list of the last value on every key list.'
def values(self):
return [self[key] for key in self.keys()]
'Yield the last value on every key list.'
def itervalues(self):
for key in self.iterkeys(): (yield self[key])