desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Test to insure that extra translations are ignored.'
def testExtraConversions(self):
query = 'SELECT * FROM raw_query_author' translations = {'something': 'else'} authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors, translations=translations)
'Make sure that an add form that is filled out, but marked for deletion doesn\'t cause validation errors.'
def test_add_form_deletion_when_invalid(self):
PoetFormSet = modelformset_factory(Poet, can_delete=True) data = {'form-TOTAL_FORMS': u'1', 'form-INITIAL_FORMS': u'0', 'form-MAX_NUM_FORMS': u'0', 'form-0-id': u'', 'form-0-name': (u'x' * 1000)} formset = PoetFormSet(data, queryset=Poet.objects.all()) self.assertEqual(formset.is_valid(), False) sel...
'Make sure that an add form that is filled out, but marked for deletion doesn\'t cause validation errors.'
def test_change_form_deletion_when_invalid(self):
PoetFormSet = modelformset_factory(Poet, can_delete=True) poet = Poet.objects.create(name='test') data = {'form-TOTAL_FORMS': u'1', 'form-INITIAL_FORMS': u'1', 'form-MAX_NUM_FORMS': u'0', 'form-0-id': unicode(poet.id), 'form-0-name': (u'x' * 1000)} formset = PoetFormSet(data, queryset=Poet.objects.all()...
'Test cases can load fixture objects into models defined in packages'
def testClassFixtures(self):
self.assertEqual(Article.objects.count(), 4) self.assertQuerysetEqual(Article.objects.all(), ['Django conquers world!', 'Copyright is fine the way it is', 'Poker has no place on ESPN', 'Python program becomes self aware'], (lambda a: a.headline))
'Fixtures can load initial data into models defined in packages'
def test_initial_data(self):
self.assertQuerysetEqual(Article.objects.all(), ['Python program becomes self aware'], (lambda a: a.headline))
'Fixtures can load data into models defined in packages'
def test_loaddata(self):
management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False) self.assertQuerysetEqual(Article.objects.all(), ['Time to reform copyright', 'Poker has no place on ESPN', 'Python program becomes self aware'], (lambda a: a.headline)) management.call_command...
'Check that test case has installed 4 fixture objects'
def testClassFixtures(self):
self.assertEqual(Article.objects.count(), 4) self.assertQuerysetEqual(Article.objects.all(), ['<Article: Django conquers world!>', '<Article: Copyright is fine the way it is>', '<Article: Poker has no place on ESPN>', '<Article: Python program becomes ...
'Helper to create a complete tree.'
def create_tree(self, stringtree):
names = stringtree.split() models = [Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species] assert (len(names) == len(models)), (names, models) parent = None for (name, model) in zip(names, models): try: obj = model.objects.get(name=name) except model.DoesNotExist...
'Normally, accessing FKs doesn\'t fill in related objects'
def test_access_fks_without_select_related(self):
def test(): fly = Species.objects.get(name='melanogaster') domain = fly.genus.family.order.klass.phylum.kingdom.domain self.assertEqual(domain.name, 'Eukaryota') self.assertNumQueries(8, test)
'A select_related() call will fill in those related objects without any extra queries'
def test_access_fks_with_select_related(self):
def test(): person = Species.objects.select_related(depth=10).get(name='sapiens') domain = person.genus.family.order.klass.phylum.kingdom.domain self.assertEqual(domain.name, 'Eukaryota') self.assertNumQueries(1, test)
'select_related() also of course applies to entire lists, not just items. This test verifies the expected behavior without select_related.'
def test_list_without_select_related(self):
def test(): world = Species.objects.all() families = [o.genus.family.name for o in world] self.assertEqual(sorted(families), ['Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae']) self.assertNumQueries(9, test)
'select_related() also of course applies to entire lists, not just items. This test verifies the expected behavior with select_related.'
def test_list_with_select_related(self):
def test(): world = Species.objects.all().select_related() families = [o.genus.family.name for o in world] self.assertEqual(sorted(families), ['Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae']) self.assertNumQueries(1, test)
'The "depth" argument to select_related() will stop the descent at a particular level.'
def test_depth(self, depth=1, expected=7):
def test(): pea = Species.objects.select_related(depth=depth).get(name='sativum') self.assertEqual(pea.genus.family.order.klass.phylum.kingdom.domain.name, 'Eukaryota') self.assertNumQueries(expected, test)
'The "depth" argument to select_related() will stop the descent at a particular level. This tests a larger depth value.'
def test_larger_depth(self):
self.test_depth(depth=5, expected=3)
'The "depth" argument to select_related() will stop the descent at a particular level. This can be used on lists as well.'
def test_list_with_depth(self):
def test(): world = Species.objects.all().select_related(depth=2) orders = [o.genus.family.order.name for o in world] self.assertEqual(sorted(orders), ['Agaricales', 'Diptera', 'Fabales', 'Primates']) self.assertNumQueries(5, test)
'The optional fields passed to select_related() control which related models we pull in. This allows for smaller queries and can act as an alternative (or, in addition to) the depth parameter. In this case, we explicitly say to select the \'genus\' and \'genus.family\' models, leading to the same number of queries as b...
def test_certain_fields(self):
def test(): world = Species.objects.select_related('genus__family') families = [o.genus.family.name for o in world] self.assertEqual(sorted(families), ['Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae']) self.assertNumQueries(1, test)
'In this case, we explicitly say to select the \'genus\' and \'genus.family\' models, leading to the same number of queries as before.'
def test_more_certain_fields(self):
def test(): world = Species.objects.filter(genus__name='Amanita').select_related('genus__family') orders = [o.genus.family.order.name for o in world] self.assertEqual(orders, [u'Agaricales']) self.assertNumQueries(2, test)
'The default behavior is to autocommit after each save() action.'
@skipUnlessDBFeature('supports_transactions') def test_autocommit(self):
self.assertRaises(Exception, self.create_a_reporter_then_fail, 'Alice', 'Smith') self.assertEqual(Reporter.objects.count(), 1)
'The autocommit decorator works exactly the same as the default behavior.'
@skipUnlessDBFeature('supports_transactions') def test_autocommit_decorator(self):
autocomitted_create_then_fail = transaction.autocommit(self.create_a_reporter_then_fail) self.assertRaises(Exception, autocomitted_create_then_fail, 'Alice', 'Smith') self.assertEqual(Reporter.objects.count(), 1)
'The autocommit decorator also works with a using argument.'
@skipUnlessDBFeature('supports_transactions') def test_autocommit_decorator_with_using(self):
autocomitted_create_then_fail = transaction.autocommit(using='default')(self.create_a_reporter_then_fail) self.assertRaises(Exception, autocomitted_create_then_fail, 'Alice', 'Smith') self.assertEqual(Reporter.objects.count(), 1)
'With the commit_on_success decorator, the transaction is only committed if the function doesn\'t throw an exception.'
@skipUnlessDBFeature('supports_transactions') def test_commit_on_success(self):
committed_on_success = transaction.commit_on_success(self.create_a_reporter_then_fail) self.assertRaises(Exception, committed_on_success, 'Dirk', 'Gently') self.assertEqual(Reporter.objects.count(), 0)
'The commit_on_success decorator also works with a using argument.'
@skipUnlessDBFeature('supports_transactions') def test_commit_on_success_with_using(self):
using_committed_on_success = transaction.commit_on_success(using='default')(self.create_a_reporter_then_fail) self.assertRaises(Exception, using_committed_on_success, 'Dirk', 'Gently') self.assertEqual(Reporter.objects.count(), 0)
'If there aren\'t any exceptions, the data will get saved.'
@skipUnlessDBFeature('supports_transactions') def test_commit_on_success_succeed(self):
Reporter.objects.create(first_name='Alice', last_name='Smith') remove_comitted_on_success = transaction.commit_on_success(self.remove_a_reporter) remove_comitted_on_success('Alice') self.assertEqual(list(Reporter.objects.all()), [])
'You can manually manage transactions if you really want to, but you have to remember to commit/rollback.'
@skipUnlessDBFeature('supports_transactions') def test_manually_managed(self):
manually_managed = transaction.commit_manually(self.manually_managed) manually_managed() self.assertEqual(Reporter.objects.count(), 1)
'If you forget, you\'ll get bad errors.'
@skipUnlessDBFeature('supports_transactions') def test_manually_managed_mistake(self):
manually_managed_mistake = transaction.commit_manually(self.manually_managed_mistake) self.assertRaises(transaction.TransactionManagementError, manually_managed_mistake)
'The commit_manually function also works with a using argument.'
@skipUnlessDBFeature('supports_transactions') def test_manually_managed_with_using(self):
using_manually_managed_mistake = transaction.commit_manually(using='default')(self.manually_managed_mistake) self.assertRaises(transaction.TransactionManagementError, using_manually_managed_mistake)
'Regression for #11900: If a function wrapped by commit_on_success writes a transaction that can\'t be committed, that transaction should be rolled back. The bug is only visible using the psycopg2 backend, though the fix is generally a good idea.'
@skipUnlessDBFeature('requires_rollback_on_dirty_transaction') def test_bad_sql(self):
execute_bad_sql = transaction.commit_on_success(self.execute_bad_sql) self.assertRaises(IntegrityError, execute_bad_sql) transaction.rollback()
'The default behavior is to autocommit after each save() action.'
@skipUnlessDBFeature('supports_transactions') def test_autocommit(self):
with self.assertRaises(Exception): self.create_reporter_and_fail() self.assertEqual(Reporter.objects.count(), 1)
'The autocommit context manager works exactly the same as the default behavior.'
@skipUnlessDBFeature('supports_transactions') def test_autocommit_context_manager(self):
with self.assertRaises(Exception): with transaction.autocommit(): self.create_reporter_and_fail() self.assertEqual(Reporter.objects.count(), 1)
'The autocommit context manager also works with a using argument.'
@skipUnlessDBFeature('supports_transactions') def test_autocommit_context_manager_with_using(self):
with self.assertRaises(Exception): with transaction.autocommit(using='default'): self.create_reporter_and_fail() self.assertEqual(Reporter.objects.count(), 1)
'With the commit_on_success context manager, the transaction is only committed if the block doesn\'t throw an exception.'
@skipUnlessDBFeature('supports_transactions') def test_commit_on_success(self):
with self.assertRaises(Exception): with transaction.commit_on_success(): self.create_reporter_and_fail() self.assertEqual(Reporter.objects.count(), 0)
'The commit_on_success context manager also works with a using argument.'
@skipUnlessDBFeature('supports_transactions') def test_commit_on_success_with_using(self):
with self.assertRaises(Exception): with transaction.commit_on_success(using='default'): self.create_reporter_and_fail() self.assertEqual(Reporter.objects.count(), 0)
'If there aren\'t any exceptions, the data will get saved.'
@skipUnlessDBFeature('supports_transactions') def test_commit_on_success_succeed(self):
Reporter.objects.create(first_name='Alice', last_name='Smith') with transaction.commit_on_success(): Reporter.objects.filter(first_name='Alice').delete() self.assertQuerysetEqual(Reporter.objects.all(), [])
'You can manually manage transactions if you really want to, but you have to remember to commit/rollback.'
@skipUnlessDBFeature('supports_transactions') def test_manually_managed(self):
with transaction.commit_manually(): Reporter.objects.create(first_name='Libby', last_name='Holtzman') transaction.commit() self.assertEqual(Reporter.objects.count(), 1)
'If you forget, you\'ll get bad errors.'
@skipUnlessDBFeature('supports_transactions') def test_manually_managed_mistake(self):
with self.assertRaises(transaction.TransactionManagementError): with transaction.commit_manually(): Reporter.objects.create(first_name='Scott', last_name='Browning')
'The commit_manually function also works with a using argument.'
@skipUnlessDBFeature('supports_transactions') def test_manually_managed_with_using(self):
with self.assertRaises(transaction.TransactionManagementError): with transaction.commit_manually(using='default'): Reporter.objects.create(first_name='Walter', last_name='Cronkite')
'Regression for #11900: If a block wrapped by commit_on_success writes a transaction that can\'t be committed, that transaction should be rolled back. The bug is only visible using the psycopg2 backend, though the fix is generally a good idea.'
@skipUnlessDBFeature('requires_rollback_on_dirty_transaction') def test_bad_sql(self):
with self.assertRaises(IntegrityError): with transaction.commit_on_success(): cursor = connection.cursor() cursor.execute("INSERT INTO transactions_reporter (first_name, last_name) VALUES ('Douglas', 'Adams');") transaction.set_dirty() transaction...
'Returns the default WSGI handler for the runner.'
def get_handler(self, *args, **options):
return WSGIHandler()
'Runs the server, using the autoreloader if needed'
def run(self, *args, **options):
use_reloader = options.get('use_reloader', True) if use_reloader: autoreload.main(self.inner_run, args, options) else: self.inner_run(*args, **options)
'Serves admin media like old-school (deprecation pending).'
def get_handler(self, *args, **options):
handler = super(Command, self).get_handler(*args, **options) return AdminMediaHandler(handler, options.get('admin_media_path', ''))
'Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field.'
def get_field_type(self, connection, table_name, row):
field_params = {} field_notes = [] try: field_type = connection.introspection.get_field_type(row[1], row) except KeyError: field_type = 'TextField' field_notes.append('This field type is a guess.') if (type(field_type) is tuple): (field_type, new_params...
'Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name.'
def get_meta(self, table_name):
return [' class Meta:', (' db_table = %r' % table_name), '']
'Return the Django version, which should be correct for all built-in Django commands. User-supplied commands should override this method.'
def get_version(self):
return django.get_version()
'Return a brief description of how to use this command, by default from the attribute ``self.help``.'
def usage(self, subcommand):
usage = ('%%prog %s [options] %s' % (subcommand, self.args)) if self.help: return ('%s\n\n%s' % (usage, self.help)) else: return usage
'Create and return the ``OptionParser`` which will be used to parse the arguments to this command.'
def create_parser(self, prog_name, subcommand):
return OptionParser(prog=prog_name, usage=self.usage(subcommand), version=self.get_version(), option_list=self.option_list)
'Print the help message for this command, derived from ``self.usage()``.'
def print_help(self, prog_name, subcommand):
parser = self.create_parser(prog_name, subcommand) parser.print_help()
'Set up any environment changes requested (e.g., Python path and Django settings), then run this command.'
def run_from_argv(self, argv):
parser = self.create_parser(argv[0], argv[1]) (options, args) = parser.parse_args(argv[2:]) handle_default_options(options) self.execute(*args, **options.__dict__)
'Try to execute this command, performing model validation if needed (as controlled by the attribute ``self.requires_model_validation``). If the command raises a ``CommandError``, intercept it and print it sensibly to stderr.'
def execute(self, *args, **options):
if self.can_import_settings: try: from django.utils import translation translation.activate('en-us') except ImportError as e: sys.stderr.write(smart_str(self.style.ERROR(('Error: %s\n' % e)))) sys.exit(1) try: self.stdout = options.get('...
'Validates the given app, raising CommandError for any errors. If app is None, then this will validate all installed apps.'
def validate(self, app=None, display_num_errors=False):
from django.core.management.validation import get_validation_errors try: from cStringIO import StringIO except ImportError: from StringIO import StringIO s = StringIO() num_errors = get_validation_errors(s, app) if num_errors: s.seek(0) error_text = s.read() ...
'The actual logic of the command. Subclasses must implement this method.'
def handle(self, *args, **options):
raise NotImplementedError()
'Perform the command\'s actions for ``app``, which will be the Python module corresponding to an application name given on the command line.'
def handle_app(self, app, **options):
raise NotImplementedError()
'Perform the command\'s actions for ``label``, which will be the string as given on the command line.'
def handle_label(self, label, **options):
raise NotImplementedError()
'Perform this command\'s actions.'
def handle_noargs(self, **options):
raise NotImplementedError()
'Output nothing. The lax options are included in the normal option parser, so under normal usage, we don\'t need to print the lax options.'
def print_help(self):
pass
'Output the basic options available to every command. This just redirects to the default print_help() behaviour.'
def print_lax_help(self):
OptionParser.print_help(self)
'Overrides OptionParser._process_args to exclusively handle default options and ignore args and other options. This overrides the behavior of the super class, which stop parsing at the first unrecognized option.'
def _process_args(self, largs, rargs, values):
while rargs: arg = rargs[0] try: if ((arg[0:2] == '--') and (len(arg) > 2)): self._process_long_opt(rargs, values) elif ((arg[:1] == '-') and (len(arg) > 1)): self._process_short_opts(rargs, values) else: del rargs[0...
'Returns the script\'s main help text, as a string.'
def main_help_text(self):
usage = ['', ("Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name), ''] usage.append('Available subcommands:') commands = get_commands().keys() commands.sort() for cmd in commands: usage.append((' %s' % cmd)) return '\n'....
'Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin.py" or "manage.py") if it can\'t be found.'
def fetch_command(self, subcommand):
try: app_name = get_commands()[subcommand] except KeyError: sys.stderr.write(("Unknown command: %r\nType '%s help' for usage.\n" % (subcommand, self.prog_name))) sys.exit(1) if isinstance(app_name, BaseCommand): klass = app_name else: klass = loa...
'Output completion suggestions for BASH. The output of this function is passed to BASH\'s `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used to get information about the cli input. Pl...
def autocomplete(self):
if (not os.environ.has_key('DJANGO_AUTO_COMPLETE')): return cwords = os.environ['COMP_WORDS'].split()[1:] cword = int(os.environ['COMP_CWORD']) try: curr = cwords[(cword - 1)] except IndexError: curr = '' subcommands = (get_commands().keys() + ['help']) options = [('-...
'Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it.'
def execute(self):
parser = LaxOptionParser(usage='%prog subcommand [options] [args]', version=get_version(), option_list=BaseCommand.option_list) self.autocomplete() try: (options, args) = parser.parse_args(self.argv) handle_default_options(options) except: pass try: subcomman...
'Return the total number of headers, including duplicates.'
def __len__(self):
return len(self._headers)
'Set the value of a header.'
def __setitem__(self, name, val):
del self[name] self._headers.append((name, val))
'Delete all occurrences of a header, if present. Does *not* raise an exception if the header is missing.'
def __delitem__(self, name):
name = name.lower() self._headers[:] = [kv for kv in self._headers if (kv[0].lower() != name)]
'Get the first header value for \'name\' Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, the first exactly which occurrance gets returned is undefined. Use getall() to get all the values matching a header field name.'
def __getitem__(self, name):
return self.get(name)
'Return true if the message contains the header.'
def has_key(self, name):
return (self.get(name) is not None)
'Return a list of all the values for the named field. These will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no fields exist with the given name, returns an emp...
def get_all(self, name):
name = name.lower() return [kv[1] for kv in self._headers if (kv[0].lower() == name)]
'Get the first header value for \'name\', or return \'default\''
def get(self, name, default=None):
name = name.lower() for (k, v) in self._headers: if (k.lower() == name): return v return default
'Return a list of all the header field names. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.'
def keys(self):
return [k for (k, v) in self._headers]
'Return a list of all header values. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.'
def values(self):
return [v for (k, v) in self._headers]
'Get all the header fields and values. These will be sorted in the order they were in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.'
def items(self):
return self._headers[:]
'str() returns the formatted headers, complete with end line, suitable for direct HTTP transmission.'
def __str__(self):
return '\r\n'.join(([('%s: %s' % kv) for kv in self._headers] + ['', '']))
'Return first matching header value for \'name\', or \'value\' If there is no header named \'name\', add a new header with name \'name\' and value \'value\'.'
def setdefault(self, name, value):
result = self.get(name) if (result is None): self._headers.append((name, value)) return value else: return result
'Extended header setting. _name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. Example: h.add_header(\...
def add_header(self, _name, _value, **_params):
parts = [] if (_value is not None): parts.append(_value) for (k, v) in _params.items(): if (v is None): parts.append(k.replace('_', '-')) else: parts.append(_formatparam(k.replace('_', '-'), v)) self._headers.append((_name, '; '.join(parts)))
'Invoke the application'
def run(self, application):
try: self.setup_environ() self.result = application(self.environ, self.start_response) self.finish_response() except: try: self.handle_error() except: self.close() raise
'Set up the environment for one request'
def setup_environ(self):
env = self.environ = self.os_environ.copy() self.add_cgi_vars() env['wsgi.input'] = self.get_stdin() env['wsgi.errors'] = self.get_stderr() env['wsgi.version'] = self.wsgi_version env['wsgi.run_once'] = self.wsgi_run_once env['wsgi.url_scheme'] = self.get_scheme() env['wsgi.multithread']...
'Send any iterable data, then close self and the iterable Subclasses intended for use in asynchronous servers will want to redefine this method, such that it sets up callbacks in the event loop to iterate over the data, and to call \'self.close()\' once the response is finished.'
def finish_response(self):
if ((not self.result_is_file()) or (not self.sendfile())): for data in self.result: self.write(data) self.finish_content() self.close()
'Return the URL scheme being used'
def get_scheme(self):
return guess_scheme(self.environ)
'Compute Content-Length or switch to chunked encoding if possible'
def set_content_length(self):
try: blocks = len(self.result) except (TypeError, AttributeError, NotImplementedError): pass else: if (blocks == 1): self.headers['Content-Length'] = str(self.bytes_sent) return
'Make any necessary header changes or defaults Subclasses can extend this to add other defaults.'
def cleanup_headers(self):
if ('Content-Length' not in self.headers): self.set_content_length()
'\'start_response()\' callable as specified by PEP 333'
def start_response(self, status, headers, exc_info=None):
if exc_info: try: if self.headers_sent: raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None elif (self.headers is not None): raise AssertionError('Headers already set!') assert isinstance(status, str), 'Status must ...
'Transmit version/status/date/server, via self._write()'
def send_preamble(self):
if self.origin_server: if self.client_is_modern(): self._write(('HTTP/%s %s\r\n' % (self.http_version, self.status))) if ('Date' not in self.headers): self._write(('Date: %s\r\n' % http_date())) if (self.server_software and ('Server' not in self.head...
'\'write()\' callable as specified by PEP 333'
def write(self, data):
assert isinstance(data, str), 'write() argument must be string' if (not self.status): raise AssertionError('write() before start_response()') elif (not self.headers_sent): self.bytes_sent = len(data) self.send_headers() else: self.bytes_sent += len(data)...
'Platform-specific file transmission Override this method in subclasses to support platform-specific file transmission. It is only called if the application\'s return iterable (\'self.result\') is an instance of \'self.wsgi_file_wrapper\'. This method should return a true value if it was able to actually transmit the ...
def sendfile(self):
return False
'Ensure headers and content have both been sent'
def finish_content(self):
if (not self.headers_sent): self.headers['Content-Length'] = '0' self.send_headers() else: pass
'Transmit headers to the client, via self._write()'
def send_headers(self):
self.cleanup_headers() self.headers_sent = True if ((not self.origin_server) or self.client_is_modern()): self.send_preamble() self._write(str(self.headers))
'True if \'self.result\' is an instance of \'self.wsgi_file_wrapper\''
def result_is_file(self):
wrapper = self.wsgi_file_wrapper return ((wrapper is not None) and isinstance(self.result, wrapper))
'True if client can accept status and headers'
def client_is_modern(self):
return (self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9')
'Log the \'exc_info\' tuple in the server log Subclasses may override to retarget the output or change its format.'
def log_exception(self, exc_info):
try: from traceback import print_exception stderr = self.get_stderr() print_exception(exc_info[0], exc_info[1], exc_info[2], self.traceback_limit, stderr) stderr.flush() finally: exc_info = None
'Log current error, and send error output to client if possible'
def handle_error(self):
self.log_exception(sys.exc_info()) if (not self.headers_sent): self.result = self.error_output(self.environ, self.start_response) self.finish_response()
'Override server_bind to store the server name.'
def server_bind(self):
try: HTTPServer.server_bind(self) except Exception as e: raise WSGIServerException(e) self.setup_environ()
'Handle a single HTTP request'
def handle(self):
self.raw_requestline = self.rfile.readline() if (not self.parse_request()): return handler = ServerHandler(self.rfile, self.wfile, self.get_stderr(), self.get_environ()) handler.request_handler = self handler.run(self.server.get_app())
'Returns the path to the media file on disk for the given URL. The passed URL is assumed to begin with ``self.base_url``. If the resulting file path is outside the media directory, then a ValueError is raised.'
def file_path(self, url):
relative_url = url[len(self.base_url[2]):] relative_path = urllib.url2pathname(relative_url) return safe_join(self.base_dir, relative_path)
'Checks if the path should be handled. Ignores the path if: * the host is provided as part of the base_url * the request\'s path isn\'t under the base path'
def _should_handle(self, path):
return (path.startswith(self.base_url[2]) and (not self.base_url[1]))
'Populate middleware lists from settings.MIDDLEWARE_CLASSES. Must be called after the environment is fixed (see __call__).'
def load_middleware(self):
from django.conf import settings from django.core import exceptions self._view_middleware = [] self._template_response_middleware = [] self._response_middleware = [] self._exception_middleware = [] request_middleware = [] for middleware_path in settings.MIDDLEWARE_CLASSES: try: ...
'Returns an HttpResponse object for the given HttpRequest'
def get_response(self, request):
from django.core import exceptions, urlresolvers from django.conf import settings try: urlconf = settings.ROOT_URLCONF urlresolvers.set_urlconf(urlconf) resolver = urlresolvers.RegexURLResolver('^/', urlconf) try: response = None for middleware_method ...
'Processing for any otherwise uncaught exceptions (those that will generate HTTP 500 responses). Can be overridden by subclasses who want customised 500 handling. Be *very* careful when overriding this because the error could be caused by anything, so assuming something like the database is always available would be an...
def handle_uncaught_exception(self, request, resolver, exc_info):
from django.conf import settings if settings.DEBUG_PROPAGATE_EXCEPTIONS: raise if settings.DEBUG: from django.views import debug return debug.technical_500_response(request, *exc_info) logger.error(('Internal Server Error: %s' % request.path), exc_info=exc_info, extra={'...
'Applies each of the functions in self.response_fixes to the request and response, modifying the response in the process. Returns the new response.'
def apply_response_fixes(self, request, response):
for func in self.response_fixes: response = func(request, response) return response
'Lazy loader that returns self.META dictionary'
def _get_meta(self):
if (not hasattr(self, '_meta')): self._meta = {'AUTH_TYPE': self._req.ap_auth_type, 'CONTENT_LENGTH': self._req.headers_in.get('content-length', 0), 'CONTENT_TYPE': self._req.headers_in.get('content-type'), 'GATEWAY_INTERFACE': 'CGI/1.1', 'PATH_INFO': self.path_info, 'PATH_TRANSLATED': None, 'QUERY_STRING':...
'Open a network connection. This method can be overwritten by backend implementations to open a network connection. It\'s up to the backend implementation to track the status of a network connection if it\'s needed by the backend. This method can be called by applications to force a single network connection to be used...
def open(self):
pass
'Close a network connection.'
def close(self):
pass