desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Yields the forms in the order they should be rendered'
| def __iter__(self):
| return iter(self.forms)
|
'Returns the form at the given index, based on the rendering order'
| def __getitem__(self, index):
| return self.forms[index]
|
'All formsets have a management form which is not included in the length'
| def __nonzero__(self):
| return True
|
'Returns the ManagementForm instance for this FormSet.'
| def _management_form(self):
| if self.is_bound:
form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
if (not form.is_valid()):
raise ValidationError('ManagementForm data is missing or has been tampered with')
else:
form = ManagementForm(auto_id=self.auto_id, p... |
'Returns the total number of forms in this FormSet.'
| def total_form_count(self):
| if self.is_bound:
return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
else:
initial_forms = self.initial_form_count()
total_forms = (initial_forms + self.extra)
if (initial_forms > self.max_num >= 0):
total_forms = initial_forms
elif (total_forms > self... |
'Returns the number of forms that are required in this FormSet.'
| def initial_form_count(self):
| if self.is_bound:
return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
else:
initial_forms = ((self.initial and len(self.initial)) or 0)
if (initial_forms > self.max_num >= 0):
initial_forms = self.max_num
return initial_forms
|
'Instantiates and returns the i-th form instance in a formset.'
| def _construct_form(self, i, **kwargs):
| defaults = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
if self.is_bound:
defaults['data'] = self.data
defaults['files'] = self.files
if (self.initial and (not ('initial' in kwargs))):
try:
defaults['initial'] = self.initial[i]
except IndexError:
... |
'Return a list of all the initial forms in this formset.'
| def _get_initial_forms(self):
| return self.forms[:self.initial_form_count()]
|
'Return a list of all the extra forms in this formset.'
| def _get_extra_forms(self):
| return self.forms[self.initial_form_count():]
|
'Returns a list of form.cleaned_data dicts for every form in self.forms.'
| def _get_cleaned_data(self):
| if (not self.is_valid()):
raise AttributeError(("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__))
return [form.cleaned_data for form in self.forms]
|
'Returns a list of forms that have been marked for deletion. Raises an
AttributeError if deletion is not allowed.'
| def _get_deleted_forms(self):
| if ((not self.is_valid()) or (not self.can_delete)):
raise AttributeError(("'%s' object has no attribute 'deleted_forms'" % self.__class__.__name__))
if (not hasattr(self, '_deleted_form_indexes')):
self._deleted_form_indexes = []
for i in range(0, self.total_form_count())... |
'Returns a list of form in the order specified by the incoming data.
Raises an AttributeError if ordering is not allowed.'
| def _get_ordered_forms(self):
| if ((not self.is_valid()) or (not self.can_order)):
raise AttributeError(("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__))
if (not hasattr(self, '_ordering')):
self._ordering = []
for i in range(0, self.total_form_count()):
form = self... |
'Returns an ErrorList of errors that aren\'t associated with a particular
form -- i.e., from formset.clean(). Returns an empty ErrorList if there
are none.'
| def non_form_errors(self):
| if (self._non_form_errors is not None):
return self._non_form_errors
return self.error_class()
|
'Returns a list of form.errors for every form in self.forms.'
| def _get_errors(self):
| if (self._errors is None):
self.full_clean()
return self._errors
|
'Returns True if form.errors is empty for every form in self.forms.'
| def is_valid(self):
| if (not self.is_bound):
return False
forms_valid = True
err = self.errors
for i in range(0, self.total_form_count()):
form = self.forms[i]
if self.can_delete:
if self._should_delete_form(form):
continue
if bool(self.errors[i]):
form... |
'Cleans all of self.data and populates self._errors.'
| def full_clean(self):
| self._errors = []
if (not self.is_bound):
return
for i in range(0, self.total_form_count()):
form = self.forms[i]
self._errors.append(form.errors)
try:
self.clean()
except ValidationError as e:
self._non_form_errors = self.error_class(e.messages)
|
'Hook for doing any extra formset-wide cleaning after Form.clean() has
been called on every form. Any ValidationError raised by this method
will not be associated with a particular form; it will be accesible
via formset.non_form_errors()'
| def clean(self):
| pass
|
'Returns true if data in any form differs from initial.'
| def has_changed(self):
| return any((form.has_changed() for form in self))
|
'A hook for adding extra fields on to each form instance.'
| def add_fields(self, form, index):
| if self.can_order:
if ((index is not None) and (index < self.initial_form_count())):
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), initial=(index + 1), required=False)
else:
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), required=False... |
'Returns True if the formset needs to be multipart, i.e. it
has FileInput. Otherwise, False.'
| def is_multipart(self):
| return (self.forms and self.forms[0].is_multipart())
|
'Returns this formset rendered as HTML <tr>s -- excluding the <table></table>.'
| def as_table(self):
| forms = u' '.join([form.as_table() for form in self])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
|
'Returns this formset rendered as HTML <p>s.'
| def as_p(self):
| forms = u' '.join([form.as_p() for form in self])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
|
'Returns this formset rendered as HTML <li>s.'
| def as_ul(self):
| forms = u' '.join([form.as_ul() for form in self])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
|
'For backwards-compatibility, several types of fields need to be
excluded from model validation. See the following tickets for
details: #12507, #12521, #12553'
| def _get_validation_exclusions(self):
| exclude = []
for f in self.instance._meta.fields:
field = f.name
if (field not in self.fields):
exclude.append(f.name)
elif (self._meta.fields and (field not in self._meta.fields)):
exclude.append(f.name)
elif (self._meta.exclude and (field in self._meta.e... |
'Calls the instance\'s validate_unique() method and updates the form\'s
validation errors if any were raised.'
| def validate_unique(self):
| exclude = self._get_validation_exclusions()
try:
self.instance.validate_unique(exclude=exclude)
except ValidationError as e:
self._update_errors(e.message_dict)
|
'Saves this ``form``\'s cleaned_data into model instance
``self.instance``.
If commit=True, then the changes to ``instance`` will be saved to the
database. Returns ``instance``.'
| def save(self, commit=True):
| if (self.instance.pk is None):
fail_message = 'created'
else:
fail_message = 'changed'
return save_instance(self, self.instance, self._meta.fields, fail_message, commit, construct=False)
|
'Returns the number of forms that are required in this FormSet.'
| def initial_form_count(self):
| if (not (self.data or self.files)):
return len(self.get_queryset())
return super(BaseModelFormSet, self).initial_form_count()
|
'Saves and returns a new model instance for the given form.'
| def save_new(self, form, commit=True):
| return form.save(commit=commit)
|
'Saves and returns an existing model instance for the given form.'
| def save_existing(self, form, instance, commit=True):
| return form.save(commit=commit)
|
'Saves model instances for every form, adding and changing instances
as necessary, and returns the list of instances.'
| def save(self, commit=True):
| if (not commit):
self.saved_forms = []
def save_m2m():
for form in self.saved_forms:
form.save_m2m()
self.save_m2m = save_m2m
return (self.save_existing_objects(commit) + self.save_new_objects(commit))
|
'Add a hidden field for the object\'s primary key.'
| def add_fields(self, form, index):
| from django.db.models import AutoField, OneToOneField, ForeignKey
self._pk_field = pk = self.model._meta.pk
def pk_is_not_editable(pk):
return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or (pk.rel and pk.rel.parent_link and pk_is_not_editable(pk.rel.to._meta.pk)))
if (p... |
'This method is used to convert objects into strings; it\'s used to
generate the labels for the choices presented by this object. Subclasses
can override this method to customize the display of the choices.'
| def label_from_instance(self, obj):
| return smart_unicode(obj)
|
'Returns a Media object that only contains media of the given type'
| def __getitem__(self, name):
| if (name in MEDIA_TYPES):
return Media(**{str(name): getattr(self, ('_' + name))})
raise KeyError(('Unknown media type "%s"' % name))
|
'Yields all "subwidgets" of this widget. Used only by RadioSelect to
allow template access to individual <input type="radio"> buttons.
Arguments are the same as for render().'
| def subwidgets(self, name, value, attrs=None, choices=()):
| (yield SubWidget(self, name, value, attrs, choices))
|
'Returns this Widget rendered as HTML, as a Unicode string.
The \'value\' given is not guaranteed to be valid input, so subclass
implementations should program defensively.'
| def render(self, name, value, attrs=None):
| raise NotImplementedError
|
'Helper function for building an attribute dictionary.'
| def build_attrs(self, extra_attrs=None, **kwargs):
| attrs = dict(self.attrs, **kwargs)
if extra_attrs:
attrs.update(extra_attrs)
return attrs
|
'Given a dictionary of data and this widget\'s name, returns the value
of this widget. Returns None if it\'s not provided.'
| def value_from_datadict(self, data, files, name):
| return data.get(name, None)
|
'Return True if data differs from initial.'
| def _has_changed(self, initial, data):
| if (data is None):
data_value = u''
else:
data_value = data
if (initial is None):
initial_value = u''
else:
initial_value = initial
if (force_unicode(initial_value) != force_unicode(data_value)):
return True
return False
|
'Returns the HTML ID attribute of this Widget for use by a <label>,
given the ID of the field. Returns None if no ID is available.
This hook is necessary because some widgets have multiple HTML
elements and, thus, multiple IDs. In that case, this method should
return an ID value that corresponds to the first ID in the ... | def id_for_label(self, id_):
| return id_
|
'File widgets take data from FILES, not POST'
| def value_from_datadict(self, data, files, name):
| return files.get(name, None)
|
'Given the name of the file input, return the name of the clear checkbox
input.'
| def clear_checkbox_name(self, name):
| return (name + '-clear')
|
'Given the name of the clear checkbox input, return the HTML id for it.'
| def clear_checkbox_id(self, name):
| return (name + '_id')
|
'Outputs a <ul> for this set of radio fields.'
| def render(self):
| return mark_safe((u'<ul>\n%s\n</ul>' % u'\n'.join([(u'<li>%s</li>' % force_unicode(w)) for w in self])))
|
'Returns an instance of the renderer.'
| def get_renderer(self, name, value, attrs=None, choices=()):
| if (value is None):
value = ''
str_value = force_unicode(value)
final_attrs = self.build_attrs(attrs)
choices = list(chain(self.choices, choices))
return self.renderer(name, str_value, final_attrs, choices)
|
'Given a list of rendered widgets (as strings), returns a Unicode string
representing the HTML for the whole lot.
This hook allows you to format the HTML design of the widgets, if
needed.'
| def format_output(self, rendered_widgets):
| return u''.join(rendered_widgets)
|
'Returns a list of decompressed values for the given compressed value.
The given value can be assumed to be valid, but not necessarily
non-empty.'
| def decompress(self, value):
| raise NotImplementedError('Subclasses must implement this method.')
|
'Media for a multiwidget is the combination of all media of the subwidgets'
| def _get_media(self):
| media = Media()
for w in self.widgets:
media = (media + w.media)
return media
|
'Returns a BoundField with the given name.'
| def __getitem__(self, name):
| try:
field = self.fields[name]
except KeyError:
raise KeyError(('Key %r not found in Form' % name))
return BoundField(self, field, name)
|
'Returns an ErrorDict for the data provided for the form'
| def _get_errors(self):
| if (self._errors is None):
self.full_clean()
return self._errors
|
'Returns True if the form has no errors. Otherwise, False. If errors are
being ignored, returns False.'
| def is_valid(self):
| return (self.is_bound and (not bool(self.errors)))
|
'Returns the field name with a prefix appended, if this Form has a
prefix set.
Subclasses may wish to override.'
| def add_prefix(self, field_name):
| return ((self.prefix and ('%s-%s' % (self.prefix, field_name))) or field_name)
|
'Add a \'initial\' prefix for checking dynamic initial values'
| def add_initial_prefix(self, field_name):
| return (u'initial-%s' % self.add_prefix(field_name))
|
'Helper function for outputting HTML. Used by as_table(), as_ul(), as_p().'
| def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
| top_errors = self.non_field_errors()
(output, hidden_fields) = ([], [])
for (name, field) in self.fields.items():
html_class_attr = ''
bf = self[name]
bf_errors = self.error_class([conditional_escape(error) for error in bf.errors])
if bf.is_hidden:
if bf_errors:
... |
'Returns this form rendered as HTML <tr>s -- excluding the <table></table>.'
| def as_table(self):
| return self._html_output(normal_row=u'<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>', error_row=u'<tr><td colspan="2">%s</td></tr>', row_ender=u'</td></tr>', help_text_html=u'<br /><span class="helptext">%s</span>', errors_on_separate_row=False)
|
'Returns this form rendered as HTML <li>s -- excluding the <ul></ul>.'
| def as_ul(self):
| return self._html_output(normal_row=u'<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>', error_row=u'<li>%s</li>', row_ender='</li>', help_text_html=u' <span class="helptext">%s</span>', errors_on_separate_row=False)
|
'Returns this form rendered as HTML <p>s.'
| def as_p(self):
| return self._html_output(normal_row=u'<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>', error_row=u'%s', row_ender='</p>', help_text_html=u' <span class="helptext">%s</span>', errors_on_separate_row=True)
|
'Returns an ErrorList of errors that aren\'t associated with a particular
field -- i.e., from Form.clean(). Returns an empty ErrorList if there
are none.'
| def non_field_errors(self):
| return self.errors.get(NON_FIELD_ERRORS, self.error_class())
|
'Returns the raw_value for a particular field name. This is just a
convenient wrapper around widget.value_from_datadict.'
| def _raw_value(self, fieldname):
| field = self.fields[fieldname]
prefix = self.add_prefix(fieldname)
return field.widget.value_from_datadict(self.data, self.files, prefix)
|
'Cleans all of self.data and populates self._errors and
self.cleaned_data.'
| def full_clean(self):
| self._errors = ErrorDict()
if (not self.is_bound):
return
self.cleaned_data = {}
if (self.empty_permitted and (not self.has_changed())):
return
self._clean_fields()
self._clean_form()
self._post_clean()
if self._errors:
del self.cleaned_data
|
'An internal hook for performing additional cleaning after form cleaning
is complete. Used for model validation in model forms.'
| def _post_clean(self):
| pass
|
'Hook for doing any extra form-wide cleaning after Field.clean() been
called on every field. Any ValidationError raised by this method will
not be associated with a particular field; it will have a special-case
association with the field named \'__all__\'.'
| def clean(self):
| return self.cleaned_data
|
'Returns True if data differs from initial.'
| def has_changed(self):
| return bool(self.changed_data)
|
'Provide a description of all media required to render the widgets on this form'
| def _get_media(self):
| media = Media()
for field in self.fields.values():
media = (media + field.widget.media)
return media
|
'Returns True if the form needs to be multipart-encoded, i.e. it has
FileInput. Otherwise, False.'
| def is_multipart(self):
| for field in self.fields.values():
if field.widget.needs_multipart_form:
return True
return False
|
'Returns a list of all the BoundField objects that are hidden fields.
Useful for manual form layout in templates.'
| def hidden_fields(self):
| return [field for field in self if field.is_hidden]
|
'Returns a list of BoundField objects that aren\'t hidden fields.
The opposite of the hidden_fields() method.'
| def visible_fields(self):
| return [field for field in self if (not field.is_hidden)]
|
'Renders this field as an HTML widget.'
| def __unicode__(self):
| if self.field.show_hidden_initial:
return (self.as_widget() + self.as_hidden(only_initial=True))
return self.as_widget()
|
'Yields rendered strings that comprise all widgets in this BoundField.
This really is only useful for RadioSelect widgets, so that you can
iterate over individual radio buttons in a template.'
| def __iter__(self):
| for subwidget in self.field.widget.subwidgets(self.html_name, self.value()):
(yield subwidget)
|
'Returns an ErrorList for this field. Returns an empty ErrorList
if there are none.'
| def _errors(self):
| return self.form.errors.get(self.name, self.form.error_class())
|
'Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field\'s default widget will be used.'
| def as_widget(self, widget=None, attrs=None, only_initial=False):
| if (not widget):
widget = self.field.widget
attrs = (attrs or {})
auto_id = self.auto_id
if (auto_id and ('id' not in attrs) and ('id' not in widget.attrs)):
if (not only_initial):
attrs['id'] = auto_id
else:
attrs['id'] = self.html_initial_id
if (not ... |
'Returns a string of HTML for representing this as an <input type="text">.'
| def as_text(self, attrs=None, **kwargs):
| return self.as_widget(TextInput(), attrs, **kwargs)
|
'Returns a string of HTML for representing this as a <textarea>.'
| def as_textarea(self, attrs=None, **kwargs):
| return self.as_widget(Textarea(), attrs, **kwargs)
|
'Returns a string of HTML for representing this as an <input type="hidden">.'
| def as_hidden(self, attrs=None, **kwargs):
| return self.as_widget(self.field.hidden_widget(), attrs, **kwargs)
|
'Returns the data for this BoundField, or None if it wasn\'t given.'
| def _data(self):
| return self.field.widget.value_from_datadict(self.form.data, self.form.files, self.html_name)
|
'Returns the value for this BoundField, using the initial value if
the form is not bound or the data otherwise.'
| def value(self):
| if (not self.form.is_bound):
data = self.form.initial.get(self.name, self.field.initial)
if callable(data):
data = data()
else:
data = self.field.bound_data(self.data, self.form.initial.get(self.name, self.field.initial))
return self.field.prepare_value(data)
|
'Wraps the given contents in a <label>, if the field has an ID attribute.
Does not HTML-escape the contents. If contents aren\'t given, uses the
field\'s HTML-escaped label.
If attrs are given, they\'re used as HTML attributes on the <label> tag.'
| def label_tag(self, contents=None, attrs=None):
| contents = (contents or conditional_escape(self.label))
widget = self.field.widget
id_ = (widget.attrs.get('id') or self.auto_id)
if id_:
attrs = ((attrs and flatatt(attrs)) or '')
contents = (u'<label for="%s"%s>%s</label>' % (widget.id_for_label(id_), attrs, unicode(contents)))
... |
'Returns a string of space-separated CSS classes for this field.'
| def css_classes(self, extra_classes=None):
| if hasattr(extra_classes, 'split'):
extra_classes = extra_classes.split()
extra_classes = set((extra_classes or []))
if (self.errors and hasattr(self.form, 'error_css_class')):
extra_classes.add(self.form.error_css_class)
if (self.field.required and hasattr(self.form, 'required_css_class... |
'Returns True if this BoundField\'s widget is hidden.'
| def _is_hidden(self):
| return self.field.widget.is_hidden
|
'Calculates and returns the ID attribute for this BoundField, if the
associated Form has specified auto_id. Returns an empty string otherwise.'
| def _auto_id(self):
| auto_id = self.form.auto_id
if (auto_id and ('%s' in smart_unicode(auto_id))):
return (smart_unicode(auto_id) % self.html_name)
elif auto_id:
return self.html_name
return ''
|
'Wrapper around the field widget\'s `id_for_label` method.
Useful, for example, for focusing on this field regardless of whether
it has a single widget or a MutiWidget.'
| def _id_for_label(self):
| widget = self.field.widget
id_ = (widget.attrs.get('id') or self.auto_id)
return widget.id_for_label(id_)
|
'Initialize the MultiPartParser object.
:META:
The standard ``META`` dictionary in Django request objects.
:input_data:
The raw post data, as a file-like object.
:upload_handler:
An UploadHandler instance that performs operations on the uploaded
data.
:encoding:
The encoding with which to treat the incoming data.'
| def __init__(self, META, input_data, upload_handlers, encoding=None):
| content_type = META.get('HTTP_CONTENT_TYPE', META.get('CONTENT_TYPE', ''))
if (not content_type.startswith('multipart/')):
raise MultiPartParserError(('Invalid Content-Type: %s' % content_type))
(ctypes, opts) = parse_header(content_type)
boundary = opts.get('boundary')
if ((not bounda... |
'Parse the POST data and break it into a FILES MultiValueDict and a POST
MultiValueDict.
Returns a tuple containing the POST and FILES dictionary, respectively.'
| def parse(self):
| from django.http import QueryDict
encoding = self._encoding
handlers = self._upload_handlers
if (self._content_length == 0):
return (QueryDict(MultiValueDict(), encoding=self._encoding), MultiValueDict())
for handler in handlers:
result = handler.handle_raw_input(self._input_data, se... |
'Handle all the signalling that takes place when a file is complete.'
| def handle_file_complete(self, old_field_name, counters):
| for (i, handler) in enumerate(self._upload_handlers):
file_obj = handler.file_complete(counters[i])
if file_obj:
self._files.appendlist(force_unicode(old_field_name, self._encoding, errors='replace'), file_obj)
break
|
'Cleanup filename from Internet Explorer full paths.'
| def IE_sanitize(self, filename):
| return (filename and filename[(filename.rfind('\\') + 1):].strip())
|
'Every LazyStream must have a producer when instantiated.
A producer is an iterable that returns a string each time it
is called.'
| def __init__(self, producer, length=None):
| self._producer = producer
self._empty = False
self._leftover = ''
self.length = length
self.position = 0
self._remaining = length
self._unget_history = []
|
'Used when the exact number of bytes to read is unimportant.
This procedure just returns whatever is chunk is conveniently returned
from the iterator instead. Useful to avoid unnecessary bookkeeping if
performance is an issue.'
| def next(self):
| if self._leftover:
output = self._leftover
self._leftover = ''
else:
output = self._producer.next()
self._unget_history = []
self.position += len(output)
return output
|
'Used to invalidate/disable this lazy stream.
Replaces the producer with an empty list. Any leftover bytes that have
already been read will still be reported upon read() and/or next().'
| def close(self):
| self._producer = []
|
'Places bytes back onto the front of the lazy stream.
Future calls to read() will return those bytes first. The
stream position and thus tell() will be rewound.'
| def unget(self, bytes):
| if (not bytes):
return
self._update_unget_history(len(bytes))
self.position -= len(bytes)
self._leftover = ''.join([bytes, self._leftover])
|
'Updates the unget history as a sanity check to see if we\'ve pushed
back the same number of bytes in one chunk. If we keep ungetting the
same number of bytes many times (here, 50), we\'re mostly likely in an
infinite loop of some sort. This is usually caused by a
maliciously-malformed MIME request.'
| def _update_unget_history(self, num_bytes):
| self._unget_history = ([num_bytes] + self._unget_history[:49])
number_equal = len([current_number for current_number in self._unget_history if (current_number == num_bytes)])
if (number_equal > 40):
raise SuspiciousOperation("The multipart parser got stuck, which shouldn't happe... |
'Finds a multipart boundary in data.
Should no boundry exist in the data None is returned instead. Otherwise
a tuple containing the indices of the following are returned:
* the end of current encapsulation
* the start of the next encapsulation'
| def _find_boundary(self, data, eof=False):
| index = self._fs(data)
if (index < 0):
return None
else:
end = index
next = (index + len(self._boundary))
if (data[max(0, (end - 1))] == '\n'):
end -= 1
if (data[max(0, (end - 1))] == '\r'):
end -= 1
return (end, next)
|
'Returns the HTTP host using the environment or request headers.'
| def get_host(self):
| if (settings.USE_X_FORWARDED_HOST and ('HTTP_X_FORWARDED_HOST' in self.META)):
host = self.META['HTTP_X_FORWARDED_HOST']
elif ('HTTP_HOST' in self.META):
host = self.META['HTTP_HOST']
else:
host = self.META['SERVER_NAME']
server_port = str(self.META['SERVER_PORT'])
if... |
'Attempts to return a signed cookie. If the signature fails or the
cookie has expired, raises an exception... unless you provide the
default argument in which case that value will be returned instead.'
| def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
| try:
cookie_value = self.COOKIES[key].encode('utf-8')
except KeyError:
if (default is not RAISE_ERROR):
return default
else:
raise
try:
value = signing.get_cookie_signer(salt=(key + salt)).unsign(cookie_value, max_age=max_age)
except signing.BadSig... |
'Builds an absolute URI from the location and the variables available in
this request. If no location is specified, the absolute URI is built on
``request.get_full_path()``.'
| def build_absolute_uri(self, location=None):
| if (not location):
location = self.get_full_path()
if (not absolute_http_url_re.match(location)):
current_uri = ('%s://%s%s' % (((self.is_secure() and 'https') or 'http'), self.get_host(), self.path))
location = urljoin(current_uri, location)
return iri_to_uri(location)
|
'Sets the encoding used for GET/POST accesses. If the GET or POST
dictionary has already been created, it is removed and recreated on the
next access (so that it is decoded correctly).'
| def _set_encoding(self, val):
| self._encoding = val
if hasattr(self, '_get'):
del self._get
if hasattr(self, '_post'):
del self._post
|
'Returns a tuple of (POST QueryDict, FILES MultiValueDict).'
| def parse_file_upload(self, META, post_data):
| self.upload_handlers = ImmutableList(self.upload_handlers, warning='You cannot alter upload handlers after the upload has been processed.')
parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
return parser.parse()
|
'Returns a mutable copy of this object.'
| def copy(self):
| return self.__deepcopy__({})
|
'Returns an encoded string of all query string arguments.
:arg safe: Used to specify characters which do not require quoting, for
example::
>>> q = QueryDict(\'\', mutable=True)
>>> q[\'next\'] = \'/a&b/\'
>>> q.urlencode()
\'next=%2Fa%26b%2F\'
>>> q.urlencode(safe=\'/\')
\'next=/a%26b/\''
| def urlencode(self, safe=None):
| output = []
if safe:
encode = (lambda k, v: ('%s=%s' % (quote(k, safe), quote(v, safe))))
else:
encode = (lambda k, v: urlencode({k: v}))
for (k, list_) in self.lists():
k = smart_str(k, self.encoding)
output.extend([encode(k, smart_str(v, self.encoding)) for v in list_])... |
'Full HTTP message, including headers.'
| def __str__(self):
| return (('\n'.join([('%s: %s' % (key, value)) for (key, value) in self._headers.values()]) + '\n\n') + self.content)
|
'Converts all values to ascii strings.'
| def _convert_to_ascii(self, *values):
| for value in values:
if isinstance(value, unicode):
try:
value = value.encode('us-ascii')
except UnicodeError as e:
e.reason += ', HTTP response headers must be in US-ASCII format'
raise
else:
... |
'Case-insensitive check for a header.'
| def has_header(self, header):
| return (header.lower() in self._headers)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.