desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Tests that serialized strings without PKs can be turned into models'
def test_pkless_serialized_strings(self):
deserial_objs = list(serializers.deserialize(self.serializer_name, self.pkless_str)) for obj in deserial_objs: self.assertFalse(obj.object.id) obj.save() self.assertEqual(Category.objects.all().count(), 4)
'Tests that objects ids can be referenced before they are defined in the serialization data.'
def test_forward_refs(self):
transaction.enter_transaction_management() transaction.managed(True) objs = serializers.deserialize(self.serializer_name, self.fwd_ref_str) with connection.constraint_checks_disabled(): for obj in objs: obj.save() transaction.commit() transaction.leave_transaction_management(...
'ModelForm test of unique_together constraint'
def test_unique_together(self):
form = PriceForm({'price': '6.00', 'quantity': '1'}) self.assertTrue(form.is_valid()) form.save() form = PriceForm({'price': '6.00', 'quantity': '1'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], [u'Price with this ...
'Test for primary_key being in the form and failing validation.'
def test_explicitpk_unspecified(self):
form = ExplicitPKForm({'key': u'', 'desc': u''}) self.assertFalse(form.is_valid())
'Ensure keys and blank character strings are tested for uniqueness.'
def test_explicitpk_unique(self):
form = ExplicitPKForm({'key': u'key1', 'desc': u''}) self.assertTrue(form.is_valid()) form.save() form = ExplicitPKForm({'key': u'key1', 'desc': u''}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 3) self.assertEqual(form.errors['__all__'], [u'Explicit pk with ...
'Execute the passed query against the passed model and check the output'
def assertSuccessfulRawQuery(self, model, query, expected_results, expected_annotations=(), params=[], translations=None):
results = list(model.objects.raw(query, params=params, translations=translations)) self.assertProcessed(model, results, expected_results, expected_annotations) self.assertAnnotations(results, expected_annotations)
'Compare the results of a raw query against expected results'
def assertProcessed(self, model, results, orig, expected_annotations=()):
self.assertEqual(len(results), len(orig)) for (index, item) in enumerate(results): orig_item = orig[index] for annotation in expected_annotations: setattr(orig_item, *annotation) for field in model._meta.fields: self.assertEqual(getattr(item, field.attname), getat...
'Check that the results of a raw query contain no annotations'
def assertNoAnnotations(self, results):
self.assertAnnotations(results, ())
'Check that the passed raw query results contain the expected annotations'
def assertAnnotations(self, results, expected_annotations):
if expected_annotations: for (index, result) in enumerate(results): (annotation, value) = expected_annotations[index] self.assertTrue(hasattr(result, annotation)) self.assertEqual(getattr(result, annotation), value)
'Basic test of raw query with a simple database query'
def testSimpleRawQuery(self):
query = 'SELECT * FROM raw_query_author' authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors)
'Raw queries are lazy: they aren\'t actually executed until they\'re iterated over.'
def testRawQueryLazy(self):
q = Author.objects.raw('SELECT * FROM raw_query_author') self.assertTrue((q.query.cursor is None)) list(q) self.assertTrue((q.query.cursor is not None))
'Test of a simple raw query against a model containing a foreign key'
def testFkeyRawQuery(self):
query = 'SELECT * FROM raw_query_book' books = Book.objects.all() self.assertSuccessfulRawQuery(Book, query, books)
'Test of a simple raw query against a model containing a field with db_column defined.'
def testDBColumnHandler(self):
query = 'SELECT * FROM raw_query_coffee' coffees = Coffee.objects.all() self.assertSuccessfulRawQuery(Coffee, query, coffees)
'Test of raw raw query\'s tolerance for columns being returned in any order'
def testOrderHandler(self):
selects = ('dob, last_name, first_name, id', 'last_name, dob, first_name, id', 'first_name, last_name, dob, id') for select in selects: query = ('SELECT %s FROM raw_query_author' % select) authors = Author.objects.all() self.assertSuccessfulRawQuery(Au...
'Test of raw query\'s optional ability to translate unexpected result column names to specific model fields'
def testTranslations(self):
query = 'SELECT first_name AS first, last_name AS last, dob, id FROM raw_query_author' translations = {'first': 'first_name', 'last': 'last_name'} authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors, translations=translations)
'Test passing optional query parameters'
def testParams(self):
query = 'SELECT * FROM raw_query_author WHERE first_name = %s' author = Author.objects.all()[2] params = [author.first_name] results = list(Author.objects.raw(query, params=params)) self.assertProcessed(Author, results, [author]) self.assertNoAnnotations(results) self.as...
'Test of a simple raw query against a model containing a m2m field'
def testManyToMany(self):
query = 'SELECT * FROM raw_query_reviewer' reviewers = Reviewer.objects.all() self.assertSuccessfulRawQuery(Reviewer, query, reviewers)
'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 that model_formset respects fields and exclude parameters of custom form'
def test_custom_form(self):
class PostForm1(forms.ModelForm, ): class Meta: model = Post fields = ('title', 'posted') class PostForm2(forms.ModelForm, ): class Meta: model = Post exclude = ('subtitle',) PostFormSet = modelformset_factory(Post, form=PostForm1) formset ...
'Test that ugettext_lazy objects work when saving model instances through various methods. Refs #10498.'
def test_create_relation_with_ugettext_lazy(self):
notlazy = u'test' lazy = ugettext_lazy(notlazy) reporter = Article.objects.create(headline=lazy, pub_date=datetime.now()) article = Article.objects.get() self.assertEqual(article.headline, notlazy) article.headline = lazy article.save() self.assertEqual(article.headline, notlazy) Art...
'Test cases can load fixture objects into models defined in packages'
def testClassFixtures(self):
self.assertEqual(Article.objects.count(), 3) self.assertQuerysetEqual(Article.objects.all(), [u'Django conquers world!', u'Copyright is fine the way it is', u'Poker has no place on ESPN'], (lambda a: a.headline))
'Fixtures can load initial data into models defined in packages'
def test_initial_data(self):
self.assertQuerysetEqual(Book.objects.all(), [u'Achieving self-awareness of Python programs'], (lambda a: a.name))
'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(), [u'Time to reform copyright', u'Poker has no place on ESPN'], (lambda a: a.headline)) management.call_command('loaddata', 'fixture2.json', verbosity=0, comm...
'Check that test case has installed 3 fixture objects'
def testClassFixtures(self):
self.assertEqual(Article.objects.count(), 3) self.assertQuerysetEqual(Article.objects.all(), ['<Article: Django conquers world!>', '<Article: Copyright is fine the way it is>', '<Article: Poker has no place on ESPN>'])
'Verifies that loading a fixture which contains an invalid object outputs an error message which contains the pk of the object that triggered the error.'
def test_loaddata_error_message(self):
if (connection.vendor == 'mysql'): connection.cursor().execute("SET sql_mode = 'TRADITIONAL'") new_io = StringIO.StringIO() management.call_command('loaddata', 'invalid.json', verbosity=0, stderr=new_io, commit=False) output = new_io.getvalue().strip().split('\n') self.assertRegexpM...
'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):
with self.assertNumQueries(8): fly = Species.objects.get(name='melanogaster') domain = fly.genus.family.order.klass.phylum.kingdom.domain self.assertEqual(domain.name, 'Eukaryota')
'A select_related() call will fill in those related objects without any extra queries'
def test_access_fks_with_select_related(self):
with self.assertNumQueries(1): person = Species.objects.select_related(depth=10).get(name='sapiens') domain = person.genus.family.order.klass.phylum.kingdom.domain self.assertEqual(domain.name, 'Eukaryota')
'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):
with self.assertNumQueries(9): world = Species.objects.all() families = [o.genus.family.name for o in world] self.assertEqual(sorted(families), ['Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae'])
'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):
with self.assertNumQueries(1): world = Species.objects.all().select_related() families = [o.genus.family.name for o in world] self.assertEqual(sorted(families), ['Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae'])
'The "depth" argument to select_related() will stop the descent at a particular level.'
def test_depth(self, depth=1, expected=7):
with self.assertNumQueries(expected): pea = Species.objects.select_related(depth=depth).get(name='sativum') self.assertEqual(pea.genus.family.order.klass.phylum.kingdom.domain.name, 'Eukaryota')
'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):
with self.assertNumQueries(5): 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'])
'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):
with self.assertNumQueries(1): world = Species.objects.select_related('genus__family') families = [o.genus.family.name for o in world] self.assertEqual(sorted(families), ['Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae'])
'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):
with self.assertNumQueries(2): 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'])
'Ensure that \'pk\' works as an ordering option in Meta. Refs #8291.'
def test_order_by_pk(self):
a1 = ArticlePKOrdering.objects.create(pk=1, headline='Article 1', pub_date=datetime(2005, 7, 26)) a2 = ArticlePKOrdering.objects.create(pk=2, headline='Article 2', pub_date=datetime(2005, 7, 27)) a3 = ArticlePKOrdering.objects.create(pk=3, headline='Article 3', pub_date=datetime(2005, 7, 27)) a...
'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 get_internal_wsgi_application()
'Runs the server, using the autoreloader if needed'
def run(self, *args, **options):
use_reloader = options.get('use_reloader') 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'))
'Pre-parse the command line to extract the value of the --testrunner option. This allows a test runner to define additional command line arguments.'
def run_from_argv(self, argv):
option = '--testrunner=' for arg in argv[2:]: if arg.startswith(option): self.test_runner = arg[len(option):] break super(Command, self).run_from_argv(argv)
'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):
show_traceback = options.get('traceback', False) saved_lang = None if self.can_import_settings: try: from django.utils import translation saved_lang = translation.get_language() translation.activate('en-us') except ImportError as e: if show_tra...
'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() behavior.'
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, commands_only=False):
if commands_only: usage = sorted(get_commands().keys()) else: usage = ['', ("Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name), '', 'Available subcommands:'] commands_dict = collections.defaultdict((lambda : [])) for (...
'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 ('DJANGO_AUTO_COMPLETE' not in os.environ): 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 = [('--help'...
'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...
'Determines where the app or project templates are. Use django.__path__[0] as the default because we don\'t know into which directory Django has been installed.'
def handle_template(self, template, subdir):
if (template is None): return path.join(django.__path__[0], 'conf', subdir) else: if template.startswith('file://'): template = template[7:] expanded_template = path.expanduser(template) expanded_template = path.normpath(expanded_template) if path.isdir(expand...
'Downloads the given URL and returns the file name.'
def download(self, url):
def cleanup_url(url): tmp = url.rstrip('/') filename = tmp.split('/')[(-1)] if url.endswith('/'): display_url = (tmp + '/') else: display_url = url return (filename, display_url) prefix = ('django_%s_template_' % self.app_or_project) tempdir = ...
'Like os.path.splitext, but takes off .tar, too'
def splitext(self, the_path):
(base, ext) = posixpath.splitext(the_path) if base.lower().endswith('.tar'): ext = (base[(-4):] + ext) base = base[:(-4)] return (base, ext)
'Extracts the given file to a temporarily and returns the path of the directory with the extracted content.'
def extract(self, filename):
prefix = ('django_%s_template_' % self.app_or_project) tempdir = tempfile.mkdtemp(prefix=prefix, suffix='_extract') self.paths_to_remove.append(tempdir) if (self.verbosity >= 2): self.stdout.write(('Extracting %s\n' % filename)) try: archive.extract(filename, tempdir) retu...
'Returns True if the name looks like a URL'
def is_url(self, template):
if (':' not in template): return False scheme = template.split(':', 1)[0].lower() return (scheme in self.url_schemes)
'Make sure that the file is writeable. Useful if our source is read-only.'
def make_writeable(self, filename):
if sys.platform.startswith('java'): return if (not os.access(filename, os.W_OK)): st = os.stat(filename) new_permissions = (stat.S_IMODE(st.st_mode) | stat.S_IWUSR) os.chmod(filename, new_permissions)
'\'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)...
'Override server_bind to store the server name.'
def server_bind(self):
try: super(WSGIServer, self).server_bind() except Exception as e: raise WSGIServerException(e) self.setup_environ()
'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__ in subclasses).'
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 logger.error('Internal Server Error: %s', request.path, exc_info=exc_info, extra={'status_code': 500, 'request': request}) if settings.DEBUG: from django.views import debug return debug.techni...
'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
'Sends one or more EmailMessage objects and returns the number of email messages sent.'
def send_messages(self, email_messages):
raise NotImplementedError