desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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 = BoundField(self, field, name) bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) if bf.is_hidden: ...
'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-encrypted, 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()
'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` class 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()) limited_input_data = LimitBytes(self._input_data, self._content_length) for handler...
'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...
'Read data from the underlying file. If you ask for too much or there isn\'t anything left, this will raise an InputStreamExhausted error.'
def read(self, num_bytes=None):
if (self.remaining <= 0): raise InputStreamExhausted() if (num_bytes is None): num_bytes = self.remaining else: num_bytes = min(num_bytes, self.remaining) self.remaining -= num_bytes return self._file.read(num_bytes)
'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...
'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 self._headers.has_key(header.lower())
'Sets a cookie. ``expires`` can be a string in the correct format or a ``datetime.datetime`` object in UTC. If ``expires`` is a datetime object then ``max_age`` will be calculated.'
def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False):
self.cookies[key] = value if (expires is not None): if isinstance(expires, datetime.datetime): delta = (expires - expires.utcnow()) delta = (delta + datetime.timedelta(seconds=1)) expires = None max_age = max(0, ((delta.days * 86400) + delta.seconds)) ...
'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):
try: settings_module = os.environ[ENVIRONMENT_VARIABLE] if (not settings_module): raise KeyError except KeyError: raise ImportError(('Settings cannot be imported, because environment variable %s is undefined.' % ENVIRONMENT_VARIABLE)) self._wrap...
'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 != None): raise RuntimeError('Settings already configured.') holder = UserSettingsHolder(default_settings) for (name, value) in options.items(): setattr(holder, name, value) self._wrapped = holder
'Returns True if the settings have already been configured.'
def configured(self):
return bool(self._wrapped)
'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.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 do a \'xml-comparision\' of want and got. Plain string comparision doesn\'t always work because, for example, attribute ordering should not be important. Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py'
def check_output_xml(self, want, got, optionsflags):
_norm_whitespace_re = re.compile('[ \\t\\n][ \\t\\n]+') def norm_whitespace(v): return _norm_whitespace_re.sub(' ', v) def child_text(element): return ''.join([c.data for c in element.childNodes if (c.nodeType == Node.TEXT_NODE)]) def children(element): return [c for c i...
'Tries to compare want and got as if they were JSON-encoded data'
def check_output_json(self, want, got, optionsflags):
(want, got) = self._strip_quotes(want, got) try: want_json = simplejson.loads(want) got_json = simplejson.loads(got) except: return False return (want_json == got_json)
'Strip quotes of doctests output values: >>> o = OutputChecker() >>> o._strip_quotes("\'foo\'") "foo" >>> o._strip_quotes(\'"foo"\') "foo" >>> o._strip_quotes("u\'foo\'") "foo" >>> o._strip_quotes(\'u"foo"\') "foo"'
def _strip_quotes(self, want, got):
def is_quoted_string(s): s = s.strip() return ((len(s) >= 2) and (s[0] == s[(-1)]) and (s[0] in ('"', "'"))) def is_quoted_unicode(s): s = s.strip() return ((len(s) >= 3) and (s[0] == 'u') and (s[1] == s[(-1)]) and (s[1] in ('"', "'"))) if (is_quoted_string(want) and is_quote...
'Performs any pre-test setup. This includes: * Flushing the database. * If the Test Case class has a \'fixtures\' member, installing the named fixtures. * If the Test Case class has a \'urls\' member, replace the ROOT_URLCONF with it. * Clearing the mail test outbox.'
def _pre_setup(self):
self._fixture_setup() self._urlconf_setup() mail.outbox = []
'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):
self.client = self.client_class() try: self._pre_setup() except (KeyboardInterrupt, SystemExit): raise except Exception: import sys result.addError(self, sys.exc_info()) return super(TransactionTestCase, self).__call__(result) try: self._post_teard...
'Performs any post-test things. This includes: * Putting back the original ROOT_URLCONF if it was changed. * Force closing the connection, so that the next test gets a clean cursor.'
def _post_teardown(self):
self._fixture_teardown() self._urlconf_teardown() for connection in connections.all(): connection.close()
'Saves the state of the warnings module'
def save_warnings_state(self):
self._warnings_state = get_warnings_state()
'Restores the sate of the warnings module to the state saved by save_warnings_state()'
def restore_warnings_state(self):
restore_warnings_state(self._warnings_state)
'Asserts that a response redirected to a specific URL, and that the redirect URL can be loaded. Note that assertRedirects won\'t work for external links since it uses TestClient to do a request.'
def assertRedirects(self, response, expected_url, status_code=302, target_status_code=200, host=None, msg_prefix=''):
if msg_prefix: msg_prefix += ': ' if hasattr(response, 'redirect_chain'): self.assertTrue((len(response.redirect_chain) > 0), (msg_prefix + ("Response didn't redirect as expected: Response code was %d (expected %d)" % (response.status_code, status_code)))) ...
'Asserts that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected), and that ``text`` occurs ``count`` times in the content of the response. If ``count`` is None, the count doesn\'t matter - the assertion is true if the text occurs at least once in the response...
def assertContains(self, response, text, count=None, status_code=200, msg_prefix=''):
if msg_prefix: msg_prefix += ': ' self.assertEqual(response.status_code, status_code, (msg_prefix + ("Couldn't retrieve content: Response code was %d (expected %d)" % (response.status_code, status_code)))) text = smart_str(text, response._charset) real_count = response...
'Asserts that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected), and that ``text`` doesn\'t occurs in the content of the response.'
def assertNotContains(self, response, text, status_code=200, msg_prefix=''):
if msg_prefix: msg_prefix += ': ' self.assertEqual(response.status_code, status_code, (msg_prefix + ("Couldn't retrieve content: Response code was %d (expected %d)" % (response.status_code, status_code)))) text = smart_str(text, response._charset) self.assertEqual(resp...
'Asserts that a form used to render the response has a specific field error.'
def assertFormError(self, response, form, field, errors, msg_prefix=''):
if msg_prefix: msg_prefix += ': ' contexts = to_list(response.context) if (not contexts): self.fail((msg_prefix + 'Response did not use any contexts to render the response')) errors = to_list(errors) found_form = False for (i, context) in enumerate(c...
'Asserts that the template with the provided name was used in rendering the response.'
def assertTemplateUsed(self, response, template_name, msg_prefix=''):
if msg_prefix: msg_prefix += ': ' template_names = [t.name for t in response.templates] if (not template_names): self.fail((msg_prefix + 'No templates used to render the response')) self.assertTrue((template_name in template_names), (msg_prefix + ("Template '%s' ...
'Asserts that the template with the provided name was NOT used in rendering the response.'
def assertTemplateNotUsed(self, response, template_name, msg_prefix=''):
if msg_prefix: msg_prefix += ': ' template_names = [t.name for t in response.templates] self.assertFalse((template_name in template_names), (msg_prefix + ("Template '%s' was used unexpectedly in rendering the response" % template_name)))
'The base environment for a request.'
def _base_environ(self, **request):
environ = {'HTTP_COOKIE': self.cookies.output(header='', sep='; '), 'PATH_INFO': '/', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'ws...
'Construct a generic request object.'
def request(self, **request):
return WSGIRequest(self._base_environ(**request))
'Construct a GET request'
def get(self, path, data={}, **extra):
parsed = urlparse(path) r = {'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': (urlencode(data, doseq=True) or parsed[4]), 'REQUEST_METHOD': 'GET', 'wsgi.input': FakePayload('')} r.update(extra) return self.request(**r)
'Construct a POST request.'
def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra):
post_data = self._encode_data(data, content_type) parsed = urlparse(path) r = {'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'POST', 'wsgi.input': FakePayload(post_data)} r.update(extra) return self.r...
'Construct a HEAD request.'
def head(self, path, data={}, **extra):
parsed = urlparse(path) r = {'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': (urlencode(data, doseq=True) or parsed[4]), 'REQUEST_METHOD': 'HEAD', 'wsgi.input': FakePayload('')} r.update(extra) return self.request(**r)
'Constrict an OPTIONS request'
def options(self, path, data={}, **extra):
parsed = urlparse(path) r = {'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': (urlencode(data, doseq=True) or parsed[4]), 'REQUEST_METHOD': 'OPTIONS', 'wsgi.input': FakePayload('')} r.update(extra) return self.request(**r)
'Construct a PUT request.'
def put(self, path, data={}, content_type=MULTIPART_CONTENT, **extra):
put_data = self._encode_data(data, content_type) parsed = urlparse(path) r = {'CONTENT_LENGTH': len(put_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'PUT', 'wsgi.input': FakePayload(put_data)} r.update(extra) return self.reque...
'Construct a DELETE request.'
def delete(self, path, data={}, **extra):
parsed = urlparse(path) r = {'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': (urlencode(data, doseq=True) or parsed[4]), 'REQUEST_METHOD': 'DELETE', 'wsgi.input': FakePayload('')} r.update(extra) return self.request(**r)
'Stores exceptions when they are generated by a view.'
def store_exc_info(self, **kwargs):
self.exc_info = sys.exc_info()
'Obtains the current session variables.'
def _session(self):
if ('django.contrib.sessions' in settings.INSTALLED_APPS): engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None) if cookie: return engine.SessionStore(cookie.value) return {}
'The master request method. Composes the environment dictionary and passes to the handler, returning the result of the handler. Assumes defaults for the query environment, which can be overridden using the arguments to the request.'
def request(self, **request):
environ = self._base_environ(**request) data = {} on_template_render = curry(store_rendered_templates, data) signals.template_rendered.connect(on_template_render, dispatch_uid='template-render') got_request_exception.connect(self.store_exc_info, dispatch_uid='request-exception') try: try...
'Requests a response from the server using GET.'
def get(self, path, data={}, follow=False, **extra):
response = super(Client, self).get(path, data=data, **extra) if follow: response = self._handle_redirects(response, **extra) return response
'Requests a response from the server using POST.'
def post(self, path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra):
response = super(Client, self).post(path, data=data, content_type=content_type, **extra) if follow: response = self._handle_redirects(response, **extra) return response
'Request a response from the server using HEAD.'
def head(self, path, data={}, follow=False, **extra):
response = super(Client, self).head(path, data=data, **extra) if follow: response = self._handle_redirects(response, **extra) return response
'Request a response from the server using OPTIONS.'
def options(self, path, data={}, follow=False, **extra):
response = super(Client, self).options(path, data=data, **extra) if follow: response = self._handle_redirects(response, **extra) return response
'Send a resource to the server using PUT.'
def put(self, path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra):
response = super(Client, self).put(path, data=data, content_type=content_type, **extra) if follow: response = self._handle_redirects(response, **extra) return response
'Send a DELETE request to the server.'
def delete(self, path, data={}, follow=False, **extra):
response = super(Client, self).delete(path, data=data, **extra) if follow: response = self._handle_redirects(response, **extra) return response
'Sets the Factory to appear as if it has successfully logged into a site. Returns True if login is possible; False if the provided credentials are incorrect, or the user is inactive, or if the sessions framework is not available.'
def login(self, **credentials):
user = authenticate(**credentials) if (user and user.is_active and ('django.contrib.sessions' in settings.INSTALLED_APPS)): engine = import_module(settings.SESSION_ENGINE) request = HttpRequest() if self.session: request.session = self.session else: reques...
'Removes the authenticated user\'s cookies and session object. Causes the authenticated user to be logged out.'
def logout(self):
session = import_module(settings.SESSION_ENGINE).SessionStore() session_cookie = self.cookies.get(settings.SESSION_COOKIE_NAME) if session_cookie: session.delete(session_key=session_cookie.value) self.cookies = SimpleCookie()