desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'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([six.text_type(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([six.text_type(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([six.text_type(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.exclude)):
exclude.append(f.name)
elif (field in self._errors.keys()):
exclude.append(f.name)
else:
form_field = self.fields[field]
field_value = self.cleaned_data.get(field, None)
if ((not f.blank) and (not form_field.required) and (field_value in EMPTY_VALUES)):
exclude.append(f.name)
return exclude
|
'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 = u'created'
else:
fail_message = u'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 (pk_is_not_editable(pk) or (pk.name not in form.fields)):
if form.is_bound:
pk_value = form.instance.pk
else:
try:
if (index is not None):
pk_value = self.get_queryset()[index].pk
else:
pk_value = None
except IndexError:
pk_value = None
if (isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey)):
qs = pk.rel.to._default_manager.get_query_set()
else:
qs = self.model._default_manager.get_query_set()
qs = qs.using(form.instance._state.db)
form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=HiddenInput)
super(BaseModelFormSet, self).add_fields(form, index)
|
'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_text(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, (u'_' + name))})
raise KeyError((u'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_text(initial_value) != force_text(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 widget\'s
tags.'
| 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 + u'-clear')
|
'Given the name of the clear checkbox input, return the HTML id for it.'
| def clear_checkbox_id(self, name):
| return (name + u'_id')
|
'Outputs a <ul> for this set of radio fields.'
| def render(self):
| return format_html(u'<ul>\n{0}\n</ul>', format_html_join(u'\n', u'<li>{0}</li>', [(force_text(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 = u''
str_value = force_text(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(u'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((u'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 (u'%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 = u''
bf = self[name]
bf_errors = self.error_class([conditional_escape(error) for error in bf.errors])
if bf.is_hidden:
if bf_errors:
top_errors.extend([(u'(Hidden field %s) %s' % (name, force_text(e))) for e in bf_errors])
hidden_fields.append(six.text_type(bf))
else:
css_classes = bf.css_classes()
if css_classes:
html_class_attr = (u' class="%s"' % css_classes)
if (errors_on_separate_row and bf_errors):
output.append((error_row % force_text(bf_errors)))
if bf.label:
label = conditional_escape(force_text(bf.label))
if self.label_suffix:
if (label[(-1)] not in u':?.!'):
label = format_html(u'{0}{1}', label, self.label_suffix)
label = (bf.label_tag(label) or u'')
else:
label = u''
if field.help_text:
help_text = (help_text_html % force_text(field.help_text))
else:
help_text = u''
output.append((normal_row % {u'errors': force_text(bf_errors), u'label': force_text(label), u'field': six.text_type(bf), u'help_text': help_text, u'html_class_attr': html_class_attr}))
if top_errors:
output.insert(0, (error_row % force_text(top_errors)))
if hidden_fields:
str_hidden = u''.join(hidden_fields)
if output:
last_row = output[(-1)]
if (not last_row.endswith(row_ender)):
last_row = (normal_row % {u'errors': u'', u'label': u'', u'field': u'', u'help_text': u'', u'html_class_attr': html_class_attr})
output.append(last_row)
output[(-1)] = ((last_row[:(- len(row_ender))] + str_hidden) + row_ender)
else:
output.append(str_hidden)
return mark_safe(u'\n'.join(output))
|
'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=u'</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=u'</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()
|
'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 __str__(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 (u'id' not in attrs) and (u'id' not in widget.attrs)):
if (not only_initial):
attrs[u'id'] = auto_id
else:
attrs[u'id'] = self.html_initial_id
if (not only_initial):
name = self.html_name
else:
name = self.html_initial_name
return widget.render(name, self.value(), attrs=attrs)
|
'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.
contents should be \'mark_safe\'d to avoid HTML escaping. 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(u'id') or self.auto_id)
if id_:
attrs = ((attrs and flatatt(attrs)) or u'')
contents = format_html(u'<label for="{0}"{1}>{2}</label>', widget.id_for_label(id_), attrs, contents)
return mark_safe(contents)
|
'Returns a string of space-separated CSS classes for this field.'
| def css_classes(self, extra_classes=None):
| if hasattr(extra_classes, u'split'):
extra_classes = extra_classes.split()
extra_classes = set((extra_classes or []))
if (self.errors and hasattr(self.form, u'error_css_class')):
extra_classes.add(self.form.error_css_class)
if (self.field.required and hasattr(self.form, u'required_css_class')):
extra_classes.add(self.form.required_css_class)
return u' '.join(extra_classes)
|
'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 (u'%s' in smart_text(auto_id))):
return (smart_text(auto_id) % self.html_name)
elif auto_id:
return self.html_name
return u''
|
'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(u'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(u'HTTP_CONTENT_TYPE', META.get(u'CONTENT_TYPE', u''))
if (not content_type.startswith(u'multipart/')):
raise MultiPartParserError((u'Invalid Content-Type: %s' % content_type))
(ctypes, opts) = parse_header(content_type.encode(u'ascii'))
boundary = opts.get(u'boundary')
if ((not boundary) or (not cgi.valid_boundary(boundary))):
raise MultiPartParserError((u'Invalid boundary in multipart: %s' % boundary))
try:
content_length = int(META.get(u'HTTP_CONTENT_LENGTH', META.get(u'CONTENT_LENGTH', 0)))
except (ValueError, TypeError):
content_length = 0
if (content_length < 0):
raise MultiPartParserError((u'Invalid content length: %r' % content_length))
if isinstance(boundary, six.text_type):
boundary = boundary.encode(u'ascii')
self._boundary = boundary
self._input_data = input_data
possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size]
self._chunk_size = min(([((2 ** 31) - 4)] + possible_sizes))
self._meta = META
self._encoding = (encoding or settings.DEFAULT_CHARSET)
self._content_length = content_length
self._upload_handlers = upload_handlers
|
'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(u'', encoding=self._encoding), MultiValueDict())
for handler in handlers:
result = handler.handle_raw_input(self._input_data, self._meta, self._content_length, self._boundary, encoding)
if (result is not None):
return (result[0], result[1])
self._post = QueryDict(u'', mutable=True)
self._files = MultiValueDict()
stream = LazyStream(ChunkIter(self._input_data, self._chunk_size))
old_field_name = None
counters = ([0] * len(handlers))
try:
for (item_type, meta_data, field_stream) in Parser(stream, self._boundary):
if old_field_name:
self.handle_file_complete(old_field_name, counters)
old_field_name = None
try:
disposition = meta_data[u'content-disposition'][1]
field_name = disposition[u'name'].strip()
except (KeyError, IndexError, AttributeError):
continue
transfer_encoding = meta_data.get(u'content-transfer-encoding')
if (transfer_encoding is not None):
transfer_encoding = transfer_encoding[0].strip()
field_name = force_text(field_name, encoding, errors=u'replace')
if (item_type == FIELD):
if (transfer_encoding == u'base64'):
raw_data = field_stream.read()
try:
data = str(raw_data).decode(u'base64')
except:
data = raw_data
else:
data = field_stream.read()
self._post.appendlist(field_name, force_text(data, encoding, errors=u'replace'))
elif (item_type == FILE):
file_name = disposition.get(u'filename')
if (not file_name):
continue
file_name = force_text(file_name, encoding, errors=u'replace')
file_name = self.IE_sanitize(unescape_entities(file_name))
content_type = meta_data.get(u'content-type', (u'',))[0].strip()
try:
charset = meta_data.get(u'content-type', (0, {}))[1].get(u'charset', None)
except:
charset = None
try:
content_length = int(meta_data.get(u'content-length')[0])
except (IndexError, TypeError, ValueError):
content_length = None
counters = ([0] * len(handlers))
try:
for handler in handlers:
try:
handler.new_file(field_name, file_name, content_type, content_length, charset)
except StopFutureHandlers:
break
for chunk in field_stream:
if (transfer_encoding == u'base64'):
over_bytes = (len(chunk) % 4)
if over_bytes:
over_chunk = field_stream.read((4 - over_bytes))
chunk += over_chunk
try:
chunk = base64.b64decode(chunk)
except Exception as e:
raise MultiPartParserError((u'Could not decode base64 data: %r' % e))
for (i, handler) in enumerate(handlers):
chunk_length = len(chunk)
chunk = handler.receive_data_chunk(chunk, counters[i])
counters[i] += chunk_length
if (chunk is None):
break
except SkipFile:
exhaust(field_stream)
else:
old_field_name = field_name
else:
exhaust(stream)
except StopUpload as e:
if (not e.connection_reset):
exhaust(self._input_data)
else:
exhaust(self._input_data)
for handler in handlers:
retval = handler.upload_complete()
if retval:
break
return (self._post, self._files)
|
'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_text(old_field_name, self._encoding, errors=u'replace'), file_obj)
break
|
'Cleanup filename from Internet Explorer full paths.'
| def IE_sanitize(self, filename):
| return (filename and filename[(filename.rfind(u'\\') + 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 = next(self._producer)
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(u"The multipart parser got stuck, which shouldn't happen with normal uploaded files. Check for malicious upload activity; if there is none, report this to the Django developers.")
|
'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))
last = max(0, (end - 1))
if (data[last:(last + 1)] == '\n'):
end -= 1
last = max(0, (end - 1))
if (data[last:(last + 1)] == '\r'):
end -= 1
return (end, next)
|
'HTTP headers as a bytestring.'
| def serialize_headers(self):
| headers = [(u'%s: %s' % (key, value)).encode(u'us-ascii') for (key, value) in self._headers.values()]
return '\r\n'.join(headers)
|
'Converts headers key/value to ascii/latin1 native strings.
`charset` must be \'ascii\' or \'latin-1\'. If `mime_encode` is True and
`value` value can\'t be represented in the given charset, MIME-encoding
is applied.'
| def _convert_to_charset(self, value, charset, mime_encode=False):
| if (not isinstance(value, (bytes, six.text_type))):
value = str(value)
try:
if six.PY3:
if isinstance(value, str):
value.encode(charset)
else:
value = value.decode(charset)
elif isinstance(value, str):
value.decode(charset)
else:
value = value.encode(charset)
except UnicodeError as e:
if mime_encode:
value = str(Header(value, u'utf-8').encode())
else:
e.reason += (u', HTTP response headers must be in %s format' % charset)
raise
if ((str(u'\n') in value) or (str(u'\r') in value)):
raise BadHeaderError((u"Header values can't contain newlines (got %r)" % value))
return value
|
'Case-insensitive check for a header.'
| def has_header(self, header):
| return (header.lower() in self._headers)
|
'Sets a cookie.
``expires`` can be:
- a string in the correct format,
- a naive ``datetime.datetime`` object in UTC,
- an aware ``datetime.datetime`` object in any time zone.
If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.'
| def set_cookie(self, key, value=u'', max_age=None, expires=None, path=u'/', domain=None, secure=False, httponly=False):
| self.cookies[key] = value
if (expires is not None):
if isinstance(expires, datetime.datetime):
if timezone.is_aware(expires):
expires = timezone.make_naive(expires, timezone.utc)
delta = (expires - expires.utcnow())
delta = (delta + datetime.timedelta(seconds=1))
expires = None
max_age = max(0, ((delta.days * 86400) + delta.seconds))
else:
self.cookies[key][u'expires'] = expires
if (max_age is not None):
self.cookies[key][u'max-age'] = max_age
if (not expires):
self.cookies[key][u'expires'] = cookie_date((time.time() + max_age))
if (path is not None):
self.cookies[key][u'path'] = path
if (domain is not None):
self.cookies[key][u'domain'] = domain
if secure:
self.cookies[key][u'secure'] = True
if httponly:
self.cookies[key][u'httponly'] = True
|
'Turn a value into a bytestring encoded in the output charset.'
| def make_bytes(self, value):
| if self.has_header(u'Content-Encoding'):
return bytes(value)
if isinstance(value, bytes):
return bytes(value)
if isinstance(value, six.text_type):
return bytes(value.encode(self._charset))
return force_bytes(value, self._charset)
|
'Full HTTP message, including headers, as a bytestring.'
| def serialize(self):
| return ((self.serialize_headers() + '\r\n\r\n') + self.content)
|
'Returns the HTTP host using the environment or request headers.'
| def get_host(self):
| if (settings.USE_X_FORWARDED_HOST and (u'HTTP_X_FORWARDED_HOST' in self.META)):
host = self.META[u'HTTP_X_FORWARDED_HOST']
elif (u'HTTP_HOST' in self.META):
host = self.META[u'HTTP_HOST']
else:
host = self.META[u'SERVER_NAME']
server_port = str(self.META[u'SERVER_PORT'])
if (server_port != (u'443' if self.is_secure() else u'80')):
host = (u'%s:%s' % (host, server_port))
allowed_hosts = ([u'*'] if settings.DEBUG else settings.ALLOWED_HOSTS)
if validate_host(host, allowed_hosts):
return host
else:
raise SuspiciousOperation((u'Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): %s' % host))
|
'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=u'', max_age=None):
| try:
cookie_value = self.COOKIES[key]
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.BadSignature:
if (default is not RAISE_ERROR):
return default
else:
raise
return value
|
'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 = (u'%s://%s%s' % ((u'https' if self.is_secure() else u'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).'
| @encoding.setter
def encoding(self, val):
| self._encoding = val
if hasattr(self, u'_get'):
del self._get
if hasattr(self, u'_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=u'You cannot alter upload handlers after the upload has been processed.')
parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
return parser.parse()
|
'Populate self._post and self._files if the content-type is a form type'
| def _load_post_and_files(self):
| if (self.method != u'POST'):
(self._post, self._files) = (QueryDict(u'', encoding=self._encoding), MultiValueDict())
return
if (self._read_started and (not hasattr(self, u'_body'))):
self._mark_post_parse_error()
return
if self.META.get(u'CONTENT_TYPE', u'').startswith(u'multipart/form-data'):
if hasattr(self, u'_body'):
data = BytesIO(self._body)
else:
data = self
try:
(self._post, self._files) = self.parse_file_upload(self.META, data)
except:
self._mark_post_parse_error()
raise
elif self.META.get(u'CONTENT_TYPE', u'').startswith(u'application/x-www-form-urlencoded'):
(self._post, self._files) = (QueryDict(self.body, encoding=self._encoding), MultiValueDict())
else:
(self._post, self._files) = (QueryDict(u'', encoding=self._encoding), MultiValueDict())
|
'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:
safe = force_bytes(safe, self.encoding)
encode = (lambda k, v: (u'%s=%s' % (quote(k, safe), quote(v, safe))))
else:
encode = (lambda k, v: urlencode({k: v}))
for (k, list_) in self.lists():
k = force_bytes(k, self.encoding)
output.extend([encode(k, force_bytes(v, self.encoding)) for v in list_])
return u'&'.join(output)
|
'Load the settings module pointed to by the environment variable. This
is used the first time we need any settings at all, if the user has not
previously configured the settings manually.'
| def _setup(self, name=None):
| try:
settings_module = os.environ[ENVIRONMENT_VARIABLE]
if (not settings_module):
raise KeyError
except KeyError:
desc = (('setting %s' % name) if name else 'settings')
raise ImproperlyConfigured(('Requested %s, but settings are not configured. You must either define the environment variable %s or call settings.configure() before accessing settings.' % (desc, ENVIRONMENT_VARIABLE)))
self._wrapped = Settings(settings_module)
self._configure_logging()
|
'Setup logging from LOGGING_CONFIG and LOGGING settings.'
| def _configure_logging(self):
| try:
logging.captureWarnings(True)
warnings.simplefilter('default', DeprecationWarning)
except AttributeError:
pass
if self.LOGGING_CONFIG:
from django.utils.log import DEFAULT_LOGGING
(logging_config_path, logging_config_func_name) = self.LOGGING_CONFIG.rsplit('.', 1)
logging_config_module = importlib.import_module(logging_config_path)
logging_config_func = getattr(logging_config_module, logging_config_func_name)
logging_config_func(DEFAULT_LOGGING)
if self.LOGGING:
compat_patch_logging_config(self.LOGGING)
logging_config_func(self.LOGGING)
|
'Called to manually configure the settings. The \'default_settings\'
parameter sets where to retrieve any unspecified values from (its
argument must support attribute access (__getattr__)).'
| def configure(self, default_settings=global_settings, **options):
| if (self._wrapped is not empty):
raise RuntimeError('Settings already configured.')
holder = UserSettingsHolder(default_settings)
for (name, value) in options.items():
setattr(holder, name, value)
self._wrapped = holder
self._configure_logging()
|
'Returns True if the settings have already been configured.'
| @property
def configured(self):
| return (self._wrapped is not empty)
|
'Requests for configuration variables not in this class are satisfied
from the module specified in default_settings (if possible).'
| def __init__(self, default_settings):
| self.__dict__['_deleted'] = set()
self.default_settings = default_settings
|
'Tests that 1 + 1 always equals 2.'
| def test_basic_addition(self):
| self.assertEqual((1 + 1), 2)
|
'The entry method for doctest output checking. Defers to a sequence of
child checkers'
| def check_output(self, want, got, optionflags):
| checks = (self.check_output_default, self.check_output_numeric, self.check_output_xml, self.check_output_json)
for check in checks:
if check(want, got, optionflags):
return True
return False
|
'The default comparator provided by doctest - not perfect, but good for
most purposes'
| def check_output_default(self, want, got, optionflags):
| return doctest.OutputChecker.check_output(self, want, got, optionflags)
|
'Doctest does an exact string comparison of output, which means that
some numerically equivalent values aren\'t equal. This check normalizes
* long integers (22L) so that they equal normal integers. (22)
* Decimals so that they are comparable, regardless of the change
made to __repr__ in Python 2.6.'
| def check_output_numeric(self, want, got, optionflags):
| return doctest.OutputChecker.check_output(self, normalize_decimals(normalize_long_ints(want)), normalize_decimals(normalize_long_ints(got)), optionflags)
|
'Tries to compare want and got as if they were JSON-encoded data'
| def check_output_json(self, want, got, optionsflags):
| (want, got) = strip_quotes(want, got)
try:
want_json = json.loads(want)
got_json = json.loads(got)
except Exception:
return False
return (want_json == got_json)
|
'Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren\'t required to
include a call to super().setUp().'
| def __call__(self, result=None):
| testMethod = getattr(self, self._testMethodName)
skipped = (getattr(self.__class__, u'__unittest_skip__', False) or getattr(testMethod, u'__unittest_skip__', False))
if (not skipped):
try:
self._pre_setup()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
result.addError(self, sys.exc_info())
return
super(SimpleTestCase, self).__call__(result)
if (not skipped):
try:
self._post_teardown()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
result.addError(self, sys.exc_info())
return
|
'Saves the state of the warnings module'
| def save_warnings_state(self):
| self._warnings_state = get_warnings_state()
|
'Restores the state of the warnings module to the state
saved by save_warnings_state()'
| def restore_warnings_state(self):
| restore_warnings_state(self._warnings_state)
|
'A context manager that temporarily sets a setting and reverts
back to the original value when exiting the context.'
| def settings(self, **kwargs):
| return override_settings(**kwargs)
|
'Asserts that the message in a raised exception matches the passed
value.
Args:
expected_exception: Exception class expected to be raised.
expected_message: expected error message string value.
callable_obj: Function to be called.
args: Extra args.
kwargs: Extra kwargs.'
| def assertRaisesMessage(self, expected_exception, expected_message, callable_obj=None, *args, **kwargs):
| return six.assertRaisesRegex(self, expected_exception, re.escape(expected_message), callable_obj, *args, **kwargs)
|
'Asserts that a form field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dictionary mapping valid inputs to their expected
cleaned values.
invalid: a dictionary mapping invalid inputs to one or more
raised error messages.
field_args: the args passed to instantiate the field
field_kwargs: the kwargs passed to instantiate the field
empty_value: the expected clean output for inputs in EMPTY_VALUES'
| def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value=u''):
| if (field_args is None):
field_args = []
if (field_kwargs is None):
field_kwargs = {}
required = fieldclass(*field_args, **field_kwargs)
optional = fieldclass(*field_args, **dict(field_kwargs, required=False))
for (input, output) in valid.items():
self.assertEqual(required.clean(input), output)
self.assertEqual(optional.clean(input), output)
for (input, errors) in invalid.items():
with self.assertRaises(ValidationError) as context_manager:
required.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
with self.assertRaises(ValidationError) as context_manager:
optional.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
error_required = [force_text(required.error_messages[u'required'])]
for e in EMPTY_VALUES:
with self.assertRaises(ValidationError) as context_manager:
required.clean(e)
self.assertEqual(context_manager.exception.messages, error_required)
self.assertEqual(optional.clean(e), empty_value)
if issubclass(fieldclass, CharField):
field_kwargs.update({u'min_length': 2, u'max_length': 20})
self.assertTrue(isinstance(fieldclass(*field_args, **field_kwargs), fieldclass))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.