desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns the value to use for the LIMIT when we are wanting "LIMIT
infinity". Returns None if the limit clause can be omitted in this case.'
| def no_limit_value(self):
| raise NotImplementedError
|
'Returns the value to use during an INSERT statement to specify that
the field should use its default value.'
| def pk_default_value(self):
| return 'DEFAULT'
|
'Returns the value of a CLOB column, for backends that return a locator
object that requires additional processing.'
| def process_clob(self, value):
| return value
|
'For backends that support returning the last insert ID as part
of an insert query, this method returns the SQL and params to
append to the INSERT query. The returned fragment should
contain a format string to hold the appropriate column.'
| def return_insert_id(self):
| pass
|
'Returns the SQLCompiler class corresponding to the given name,
in the namespace corresponding to the `compiler_module` attribute
on this backend.'
| def compiler(self, compiler_name):
| if (self._cache is None):
self._cache = import_module(self.compiler_module)
return getattr(self._cache, compiler_name)
|
'Returns a quoted version of the given table, index or column name. Does
not quote the given name if it\'s already been quoted.'
| def quote_name(self, name):
| raise NotImplementedError()
|
'Returns a SQL expression that returns a random value.'
| def random_function_sql(self):
| return 'RANDOM()'
|
'Returns the string to use in a query when performing regular expression
lookups (using "regex" or "iregex"). The resulting string should
contain a \'%s\' placeholder for the column being searched against.
If the feature is not supported (or part of it is not supported), a
NotImplementedError exception can be raised.'
| def regex_lookup(self, lookup_type):
| raise NotImplementedError
|
'Returns the SQL for starting a new savepoint. Only required if the
"uses_savepoints" feature is True. The "sid" parameter is a string
for the savepoint id.'
| def savepoint_create_sql(self, sid):
| raise NotImplementedError
|
'Returns the SQL for committing the given savepoint.'
| def savepoint_commit_sql(self, sid):
| raise NotImplementedError
|
'Returns the SQL for rolling back the given savepoint.'
| def savepoint_rollback_sql(self, sid):
| raise NotImplementedError
|
'Returns a list of SQL statements required to remove all data from
the given database tables (without actually removing the tables
themselves).
The `style` argument is a Style object as returned by either
color_style() or no_style() in django.core.management.color.'
| def sql_flush(self, style, tables, sequences):
| raise NotImplementedError()
|
'Returns a list of the SQL statements required to reset sequences for
the given models.
The `style` argument is a Style object as returned by either
color_style() or no_style() in django.core.management.color.'
| def sequence_reset_sql(self, style, model_list):
| return []
|
'Returns the SQL statement required to start a transaction.'
| def start_transaction_sql(self):
| return 'BEGIN;'
|
'Returns the SQL that will be appended to tables or rows to define
a tablespace. Returns \'\' if the backend doesn\'t use tablespaces.'
| def tablespace_sql(self, tablespace, inline=False):
| return ''
|
'Prepares a value for use in a LIKE query.'
| def prep_for_like_query(self, x):
| from django.utils.encoding import smart_unicode
return smart_unicode(x).replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
|
'Transform a date value to an object compatible with what is expected
by the backend driver for date columns.'
| def value_to_db_date(self, value):
| if (value is None):
return None
return datetime_safe.new_date(value).strftime('%Y-%m-%d')
|
'Transform a datetime value to an object compatible with what is expected
by the backend driver for datetime columns.'
| def value_to_db_datetime(self, value):
| if (value is None):
return None
return unicode(value)
|
'Transform a datetime value to an object compatible with what is expected
by the backend driver for time columns.'
| def value_to_db_time(self, value):
| if (value is None):
return None
return unicode(value)
|
'Transform a decimal.Decimal value to an object compatible with what is
expected by the backend driver for decimal (numeric) columns.'
| def value_to_db_decimal(self, value, max_digits, decimal_places):
| if (value is None):
return None
return util.format_number(value, max_digits, decimal_places)
|
'Returns a two-elements list with the lower and upper bound to be used
with a BETWEEN operator to query a field value using a year lookup
`value` is an int, containing the looked-up year.'
| def year_lookup_bounds(self, value):
| first = '%s-01-01 00:00:00'
second = '%s-12-31 23:59:59.999999'
return [(first % value), (second % value)]
|
'Returns a two-elements list with the lower and upper bound to be used
with a BETWEEN operator to query a DateField value using a year lookup
`value` is an int, containing the looked-up year.
By default, it just calls `self.year_lookup_bounds`. Some backends need
this hook because on their DB date fields can\'t be comp... | def year_lookup_bounds_for_date_field(self, value):
| return self.year_lookup_bounds(value)
|
'Coerce the value returned by the database backend into a consistent type that
is compatible with the field type.'
| def convert_values(self, value, field):
| internal_type = field.get_internal_type()
if (internal_type == 'DecimalField'):
return value
elif ((internal_type and internal_type.endswith('IntegerField')) or (internal_type == 'AutoField')):
return int(value)
elif (internal_type in ('DateField', 'DateTimeField', 'TimeField')):
... |
'Check that the backend supports the provided aggregate
This is used on specific backends to rule out known aggregates
that are known to have faulty implementations. If the named
aggregate function has a known problem, the backend should
raise NotImplemented.'
| def check_aggregate_support(self, aggregate_func):
| pass
|
'Combine a list of subexpressions into a single expression, using
the provided connecting operator. This is required because operators
can vary between backends (e.g., Oracle with %% and &) and between
subexpression types (e.g., date expressions)'
| def combine_expression(self, connector, sub_expressions):
| conn = (' %s ' % connector)
return conn.join(sub_expressions)
|
'Hook for a database backend to use the cursor description to
match a Django field type to a database column.
For Oracle, the column data_type on its own is insufficient to
distinguish between a FloatField and IntegerField, for example.'
| def get_field_type(self, data_type, description):
| return self.data_types_reverse[data_type]
|
'Apply a conversion to the name for the purposes of comparison.
The default table name converter is for case sensitive comparison.'
| def table_name_converter(self, name):
| return name
|
'Returns a list of names of all tables that exist in the database.'
| def table_names(self):
| cursor = self.connection.cursor()
return self.get_table_list(cursor)
|
'Returns a list of all table names that have associated Django models and
are in INSTALLED_APPS.
If only_existing is True, the resulting list will only include the tables
that actually exist in the database.'
| def django_table_names(self, only_existing=False):
| from django.db import models, router
tables = set()
for app in models.get_apps():
for model in models.get_models(app):
if (not model._meta.managed):
continue
if (not router.allow_syncdb(self.connection.alias, model)):
continue
table... |
'Returns a set of all models represented by the provided list of table names.'
| def installed_models(self, tables):
| from django.db import models, router
all_models = []
for app in models.get_apps():
for model in models.get_models(app):
if router.allow_syncdb(self.connection.alias, model):
all_models.append(model)
tables = map(self.table_name_converter, tables)
return set([m for... |
'Returns a list of information about all DB sequences for all models in all apps.'
| def sequence_list(self):
| from django.db import models, router
apps = models.get_apps()
sequence_list = []
for app in apps:
for model in models.get_models(app):
if (not model._meta.managed):
continue
if (not router.allow_syncdb(self.connection.alias, model)):
contin... |
'By default, there is no backend-specific validation'
| def validate_field(self, errors, opts, f):
| pass
|
'Confirm support for STDDEV and related stats functions
SQLite supports STDDEV as an extension package; so
connection.ops.check_aggregate_support() can\'t unilaterally
rule out support for STDDEV. We need to manually check
whether the call works.'
| def _supports_stddev(self):
| cursor = self.connection.cursor()
cursor.execute('CREATE TABLE STDDEV_TEST (X INT)')
try:
cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST')
has_support = True
except utils.DatabaseError:
has_support = False
cursor.execute('DROP TABLE STDDEV_TEST')... |
'SQLite returns floats when it should be returning decimals,
and gets dates and datetimes wrong.
For consistency with other backends, coerce when required.'
| def convert_values(self, value, field):
| internal_type = field.get_internal_type()
if (internal_type == 'DecimalField'):
return util.typecast_decimal(field.format_number(value))
elif ((internal_type and internal_type.endswith('IntegerField')) or (internal_type == 'AutoField')):
return int(value)
elif (internal_type == 'DateFiel... |
'SQLite3 doesn\'t support constraints'
| def sql_for_pending_references(self, model, style, pending_references):
| return []
|
'SQLite3 doesn\'t support constraints'
| def sql_remove_table_constraints(self, model, references_to_delete, style):
| return []
|
'Returns a list of table names in the current database.'
| def get_table_list(self, cursor):
| cursor.execute("\n SELECT name FROM sqlite_master\n WHERE type='table' AND NOT name='sqlite_sequence'\n ORDER BY name")
return [row[0] for row i... |
'Returns a description of the table, with the DB-API cursor.description interface.'
| def get_table_description(self, cursor, table_name):
| return [(info['name'], info['type'], None, None, None, None, info['null_ok']) for info in self._table_info(cursor, table_name)]
|
'Returns a dictionary of {field_index: (field_index_other_table, other_table)}
representing all relationships to the given table. Indexes are 0-based.'
| def get_relations(self, cursor, table_name):
| relations = {}
cursor.execute('SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s', [table_name, 'table'])
results = cursor.fetchone()[0].strip()
results = results[(results.index('(') + 1):results.rindex(')')]
for (field_index, field_desc) in enumerate(r... |
'Returns a dictionary of fieldname -> infodict for the given table,
where each infodict is in the format:
{\'primary_key\': boolean representing whether it\'s the primary key,
\'unique\': boolean representing whether it\'s a unique index}'
| def get_indexes(self, cursor, table_name):
| indexes = {}
for info in self._table_info(cursor, table_name):
indexes[info['name']] = {'primary_key': (info['pk'] != 0), 'unique': False}
cursor.execute(('PRAGMA index_list(%s)' % self.connection.ops.quote_name(table_name)))
for (index, unique) in [(field[1], field[2]) for field in cursor.fe... |
'Confirm support for introspected foreign keys'
| def _can_introspect_foreign_keys(self):
| cursor = self.connection.cursor()
cursor.execute('CREATE TABLE INTROSPECT_TEST (X INT)')
cursor.execute('SHOW TABLE STATUS WHERE Name="INTROSPECT_TEST"')
result = cursor.fetchone()
cursor.execute('DROP TABLE INTROSPECT_TEST')
return (result[1] != 'MyISAM')
|
'"ORDER BY NULL" prevents MySQL from implicitly ordering by grouped
columns. If no ordering would otherwise be applied, we don\'t want any
implicit sorting going on.'
| def force_no_ordering(self):
| return ['NULL']
|
'There are some field length restrictions for MySQL:
- Prior to version 5.0.3, character fields could not exceed 255
characters in length.
- No character (varchar) fields can have a length exceeding 255
characters if they have a unique index on them.'
| def validate_field(self, errors, opts, f):
| from django.db import models
db_version = self.connection.get_server_version()
varchar_fields = (models.CharField, models.CommaSeparatedIntegerField, models.SlugField)
if (isinstance(f, varchar_fields) and (f.max_length > 255)):
if (db_version < (5, 0, 3)):
msg = '"%(name)s": %(cl... |
'All inline references are pending under MySQL'
| def sql_for_inline_foreign_key_references(self, field, known_models, style):
| return ([], True)
|
'Returns a list of table names in the current database.'
| def get_table_list(self, cursor):
| cursor.execute('SHOW TABLES')
return [row[0] for row in cursor.fetchall()]
|
'Returns a description of the table, with the DB-API cursor.description interface.'
| def get_table_description(self, cursor, table_name):
| cursor.execute(('SELECT * FROM %s LIMIT 1' % self.connection.ops.quote_name(table_name)))
return cursor.description
|
'Returns a dictionary of {field_name: field_index} for the given table.
Indexes are 0-based.'
| def _name_to_index(self, cursor, table_name):
| return dict([(d[0], i) for (i, d) in enumerate(self.get_table_description(cursor, table_name))])
|
'Returns a dictionary of {field_index: (field_index_other_table, other_table)}
representing all relationships to the given table. Indexes are 0-based.'
| def get_relations(self, cursor, table_name):
| my_field_dict = self._name_to_index(cursor, table_name)
constraints = []
relations = {}
try:
cursor.execute('\n SELECT column_name, referenced_table_name, referenced_column_name\n ... |
'Returns a dictionary of fieldname -> infodict for the given table,
where each infodict is in the format:
{\'primary_key\': boolean representing whether it\'s the primary key,
\'unique\': boolean representing whether it\'s a unique index}'
| def get_indexes(self, cursor, table_name):
| cursor.execute(('SHOW INDEX FROM %s' % self.connection.ops.quote_name(table_name)))
indexes = {}
for row in cursor.fetchall():
indexes[row[4]] = {'primary_key': (row[2] == 'PRIMARY'), 'unique': (not bool(row[1]))}
return indexes
|
'implements the interval functionality for expressions
format for Postgres:
(datefield + interval \'3 days 200 seconds 5 microseconds\')'
| def date_interval_sql(self, sql, connector, timedelta):
| modifiers = []
if timedelta.days:
modifiers.append((u'%s days' % timedelta.days))
if timedelta.seconds:
modifiers.append((u'%s seconds' % timedelta.seconds))
if timedelta.microseconds:
modifiers.append((u'%s microseconds' % timedelta.microseconds))
mods = u' '.joi... |
'Check that the backend fully supports the provided aggregate.
The population and sample statistics (STDDEV_POP, STDDEV_SAMP,
VAR_POP, VAR_SAMP) were first implemented in Postgres 8.2.
The implementation of population statistics (STDDEV_POP and VAR_POP)
under Postgres 8.2 - 8.2.4 is known to be faulty. Raise
NotImpleme... | def check_aggregate_support(self, aggregate):
| if (aggregate.sql_function in ('STDDEV_POP', 'STDDEV_SAMP', 'VAR_POP', 'VAR_SAMP')):
if (self.postgres_version[0:2] < (8, 2)):
raise NotImplementedError(('PostgreSQL does not support %s prior to version 8.2. Please upgrade your version of PostgreSQL.' % ... |
'Returns the maximum length of an identifier.
Note that the maximum length of an identifier is 63 by default, but can
be changed by recompiling PostgreSQL after editing the NAMEDATALEN
macro in src/include/pg_config_manual.h .
This implementation simply returns 63, but can easily be overridden by a
custom database back... | def max_name_length(self):
| return 63
|
'Returns a list of table names in the current database.'
| def get_table_list(self, cursor):
| cursor.execute("\n SELECT c.relname\n FROM pg_catalog.pg_class c\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n ... |
'Returns a description of the table, with the DB-API cursor.description interface.'
| def get_table_description(self, cursor, table_name):
| cursor.execute(('SELECT * FROM %s LIMIT 1' % self.connection.ops.quote_name(table_name)))
return cursor.description
|
'Returns a dictionary of {field_index: (field_index_other_table, other_table)}
representing all relationships to the given table. Indexes are 0-based.'
| def get_relations(self, cursor, table_name):
| cursor.execute("\n SELECT con.conkey, con.confkey, c2.relname\n FROM pg_constraint con, pg_class c1, pg_class c2\n WHERE c1.oid = con.conre... |
'Returns a dictionary of fieldname -> infodict for the given table,
where each infodict is in the format:
{\'primary_key\': boolean representing whether it\'s the primary key,
\'unique\': boolean representing whether it\'s a unique index}'
| def get_indexes(self, cursor, table_name):
| cursor.execute('\n SELECT attr.attname, idx.indkey, idx.indisunique, idx.indisprimary\n FROM pg_catalog.pg_class c, pg_catalog.pg_class c2,\n ... |
'Generates a 32-bit digest of a set of arguments that can be used to
shorten identifying names.'
| def _digest(self, *args):
| return ('%x' % (abs(hash(args)) % 4294967296L))
|
'Returns the SQL required to create a single model, as a tuple of:
(list_of_sql, pending_references_dict)'
| def sql_create_model(self, model, style, known_models=set()):
| opts = model._meta
if ((not opts.managed) or opts.proxy):
return ([], {})
final_output = []
table_output = []
pending_references = {}
qn = self.connection.ops.quote_name
for f in opts.local_fields:
col_type = f.db_type(connection=self.connection)
tablespace = (f.db_ta... |
'Return the SQL snippet defining the foreign key reference for a field'
| def sql_for_inline_foreign_key_references(self, field, known_models, style):
| qn = self.connection.ops.quote_name
if (field.rel.to in known_models):
output = [((((((style.SQL_KEYWORD('REFERENCES') + ' ') + style.SQL_TABLE(qn(field.rel.to._meta.db_table))) + ' (') + style.SQL_FIELD(qn(field.rel.to._meta.get_field(field.rel.field_name).column))) + ')') + self.connection.ops.d... |
'Returns any ALTER TABLE statements to add constraints after the fact.'
| def sql_for_pending_references(self, model, style, pending_references):
| from django.db.backends.util import truncate_name
if ((not model._meta.managed) or model._meta.proxy):
return []
qn = self.connection.ops.quote_name
final_output = []
opts = model._meta
if (model in pending_references):
for (rel_class, f) in pending_references[model]:
... |
'Return the CREATE TABLE statments for all the many-to-many tables defined on a model'
| def sql_for_many_to_many(self, model, style):
| import warnings
warnings.warn('Database creation API for m2m tables has been deprecated. M2M models are now automatically generated', DeprecationWarning)
output = []
for f in model._meta.local_many_to_many:
if (model._meta.managed or f.rel.to._meta.manag... |
'Return the CREATE TABLE statements for a single m2m field'
| def sql_for_many_to_many_field(self, model, f, style):
| import warnings
warnings.warn('Database creation API for m2m tables has been deprecated. M2M models are now automatically generated', DeprecationWarning)
from django.db import models
from django.db.backends.util import truncate_name
output = []
if f.auto... |
'Create the references to other tables required by a many-to-many table'
| def sql_for_inline_many_to_many_references(self, model, field, style):
| import warnings
warnings.warn('Database creation API for m2m tables has been deprecated. M2M models are now automatically generated', DeprecationWarning)
from django.db import models
opts = model._meta
qn = self.connection.ops.quote_name
table_output = [... |
'Returns the CREATE INDEX SQL statements for a single model'
| def sql_indexes_for_model(self, model, style):
| if ((not model._meta.managed) or model._meta.proxy):
return []
output = []
for f in model._meta.local_fields:
output.extend(self.sql_indexes_for_field(model, f, style))
return output
|
'Return the CREATE INDEX SQL statements for a single model field'
| def sql_indexes_for_field(self, model, f, style):
| from django.db.backends.util import truncate_name
if (f.db_index and (not f.unique)):
qn = self.connection.ops.quote_name
tablespace = (f.db_tablespace or model._meta.db_tablespace)
if tablespace:
sql = self.connection.ops.tablespace_sql(tablespace)
if sql:
... |
'Return the DROP TABLE and restraint dropping statements for a single model'
| def sql_destroy_model(self, model, references_to_delete, style):
| if ((not model._meta.managed) or model._meta.proxy):
return []
qn = self.connection.ops.quote_name
output = [('%s %s;' % (style.SQL_KEYWORD('DROP TABLE'), style.SQL_TABLE(qn(model._meta.db_table))))]
if (model in references_to_delete):
output.extend(self.sql_remove_table_constraint... |
'Returns the DROP TABLE statements for a single m2m field'
| def sql_destroy_many_to_many(self, model, f, style):
| import warnings
warnings.warn('Database creation API for m2m tables has been deprecated. M2M models are now automatically generated', DeprecationWarning)
qn = self.connection.ops.quote_name
output = []
if f.auto_created:
output.append(('%s %s;' % ... |
'Creates a test database, prompting the user for confirmation if the
database already exists. Returns the name of the test database created.'
| def create_test_db(self, verbosity=1, autoclobber=False):
| from django.core.management import call_command
test_database_name = self._get_test_db_name()
if (verbosity >= 1):
test_db_repr = ''
if (verbosity >= 2):
test_db_repr = (" ('%s')" % test_database_name)
print ("Creating test database for alias '%s'%s..." ... |
'Internal implementation - returns the name of the test DB that will be
created. Only useful when called from create_test_db() and
_create_test_db() and when no external munging is done with the \'NAME\'
or \'TEST_NAME\' settings.'
| def _get_test_db_name(self):
| if self.connection.settings_dict['TEST_NAME']:
return self.connection.settings_dict['TEST_NAME']
return (TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME'])
|
'Internal implementation - creates the test db tables.'
| def _create_test_db(self, verbosity, autoclobber):
| suffix = self.sql_table_creation_suffix()
test_database_name = self._get_test_db_name()
qn = self.connection.ops.quote_name
cursor = self.connection.cursor()
self.set_autocommit()
try:
cursor.execute(('CREATE DATABASE %s %s' % (qn(test_database_name), suffix)))
except Except... |
'Destroy a test database, prompting the user for confirmation if the
database already exists. Returns the name of the test database created.'
| def destroy_test_db(self, old_database_name, verbosity=1):
| self.connection.close()
test_database_name = self.connection.settings_dict['NAME']
if (verbosity >= 1):
test_db_repr = ''
if (verbosity >= 2):
test_db_repr = (" ('%s')" % test_database_name)
print ("Destroying test database for alias '%s'%s..." % (self.c... |
'Internal implementation - remove the test db tables.'
| def _destroy_test_db(self, test_database_name, verbosity):
| cursor = self.connection.cursor()
self.set_autocommit()
time.sleep(1)
cursor.execute(('DROP DATABASE %s' % self.connection.ops.quote_name(test_database_name)))
self.connection.close()
|
'Make sure a connection is in autocommit mode.'
| def set_autocommit(self):
| if hasattr(self.connection.connection, 'autocommit'):
if callable(self.connection.connection.autocommit):
self.connection.connection.autocommit(True)
else:
self.connection.connection.autocommit = True
elif hasattr(self.connection.connection, 'set_isolation_level'):
... |
'SQL to append to the end of the test table creation statements'
| def sql_table_creation_suffix(self):
| return ''
|
'Returns a tuple with elements of self.connection.settings_dict (a
DATABASES setting value) that uniquely identify a database
accordingly to the RDBMS particularities.'
| def test_db_signature(self):
| settings_dict = self.connection.settings_dict
return (settings_dict['HOST'], settings_dict['PORT'], settings_dict['ENGINE'], settings_dict['NAME'])
|
'Puts the defaults into the settings dictionary for a given connection
where no settings is provided.'
| def ensure_defaults(self, alias):
| try:
conn = self.databases[alias]
except KeyError:
raise ConnectionDoesNotExist(("The connection %s doesn't exist" % alias))
conn.setdefault('ENGINE', 'django.db.backends.dummy')
if ((conn['ENGINE'] == 'django.db.backends.') or (not conn['ENGINE'])):
conn['ENGINE'] = ... |
'Check for denied User-Agents and rewrite the URL based on
settings.APPEND_SLASH and settings.PREPEND_WWW'
| def process_request(self, request):
| if ('HTTP_USER_AGENT' in request.META):
for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
logger.warning(('Forbidden (User agent): %s' % request.path), extra={'status_code': 403, 'request': request})
... |
'Send broken link emails and calculate the Etag, if needed.'
| def process_response(self, request, response):
| if (response.status_code == 404):
if (settings.SEND_BROKEN_LINK_EMAILS and (not settings.DEBUG)):
domain = request.get_host()
referer = request.META.get('HTTP_REFERER', None)
is_internal = _is_internal_request(domain, referer)
path = request.get_full_path()
... |
'Enters transaction management'
| def process_request(self, request):
| transaction.enter_transaction_management()
transaction.managed(True)
|
'Rolls back the database and leaves transaction management'
| def process_exception(self, request, exception):
| if transaction.is_dirty():
transaction.rollback()
transaction.leave_transaction_management()
|
'Commits and leaves transaction management.'
| def process_response(self, request, response):
| if transaction.is_managed():
if transaction.is_dirty():
transaction.commit()
transaction.leave_transaction_management()
return response
|
'If the request method is HEAD and either the IP is internal or the
user is a logged-in staff member, quickly return with an x-header
indicating the view function. This is used by the documentation module
to lookup the view function for an arbitrary page.'
| def process_view(self, request, view_func, view_args, view_kwargs):
| if ((request.method == 'HEAD') and ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS) or (request.user.is_active and request.user.is_staff))):
response = http.HttpResponse()
response['X-View'] = ('%s.%s' % (view_func.__module__, view_func.__name__))
return response
|
'Sets the cache, if needed.'
| def process_response(self, request, response):
| if (not self._should_update_cache(request, response)):
return response
if (not (response.status_code == 200)):
return response
timeout = get_max_age(response)
if (timeout == None):
timeout = self.cache_timeout
elif (timeout == 0):
return response
patch_response_he... |
'Checks whether the page is already cached and returns the cached
version if available.'
| def process_request(self, request):
| if (not (request.method in ('GET', 'HEAD'))):
request._cache_update_cache = False
return None
cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache)
if (cache_key is None):
request._cache_update_cache = True
return None
response = self.cache.get(cach... |
'Class method to parse prefix node and return a Node.'
| @classmethod
def handle_token(cls, parser, token, name):
| tokens = token.contents.split()
if ((len(tokens) > 1) and (tokens[1] != 'as')):
raise template.TemplateSyntaxError(("First argument in '%s' must be 'as'" % tokens[0]))
if (len(tokens) > 1):
varname = tokens[2]
else:
varname = None
return cls(varname, name)
|
'Returns the object the view is displaying.
By default this requires `self.queryset` and a `pk` or `slug` argument
in the URLconf, but subclasses can override this to return any object.'
| def get_object(self, queryset=None):
| if (queryset is None):
queryset = self.get_queryset()
pk = self.kwargs.get('pk', None)
slug = self.kwargs.get('slug', None)
if (pk is not None):
queryset = queryset.filter(pk=pk)
elif (slug is not None):
slug_field = self.get_slug_field()
queryset = queryset.filter(**... |
'Get the queryset to look an object up against. May not be called if
`get_object` is overridden.'
| def get_queryset(self):
| if (self.queryset is None):
if self.model:
return self.model._default_manager.all()
else:
raise ImproperlyConfigured((u'%(cls)s is missing a queryset. Define %(cls)s.model, %(cls)s.queryset, or override %(cls)s.get_object().' % {'cls': self.__cla... |
'Get the name of a slug field to be used to look up by slug.'
| def get_slug_field(self):
| return self.slug_field
|
'Get the name to use for the object.'
| def get_context_object_name(self, obj):
| if self.context_object_name:
return self.context_object_name
elif hasattr(obj, '_meta'):
return smart_str(obj._meta.object_name.lower())
else:
return None
|
'Return a list of template names to be used for the request. Must return
a list. May not be called if get_template is overridden.'
| def get_template_names(self):
| try:
names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
except ImproperlyConfigured:
names = []
if (self.object and self.template_name_field):
name = getattr(self.object, self.template_name_field, None)
if name:
names.insert(0, name)
i... |
'Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.'
| def __init__(self, **kwargs):
| for (key, value) in kwargs.iteritems():
setattr(self, key, value)
|
'Main entry point for a request-response process.'
| @classonlymethod
def as_view(cls, **initkwargs):
| for key in initkwargs:
if (key in cls.http_method_names):
raise TypeError((u"You tried to pass in the %s method name as a keyword argument to %s(). Don't do that." % (key, cls.__name__)))
if (not hasattr(cls, key)):
raise Typ... |
'Returns a response with a template rendered with the given context.'
| def render_to_response(self, context, **response_kwargs):
| return self.response_class(request=self.request, template=self.get_template_names(), context=context, **response_kwargs)
|
'Returns a list of template names to be used for the request. Must return
a list. May not be called if render_to_response is overridden.'
| def get_template_names(self):
| if (self.template_name is None):
raise ImproperlyConfigured("TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'")
else:
return [self.template_name]
|
'Return the URL redirect to. Keyword arguments from the
URL pattern match generating the redirect request
are provided as kwargs to this method.'
| def get_redirect_url(self, **kwargs):
| if self.url:
args = self.request.META['QUERY_STRING']
if (args and self.query_string):
url = ('%s?%s' % (self.url, args))
else:
url = self.url
return (url % kwargs)
else:
return None
|
'Get a year format string in strptime syntax to be used to parse the
year from url variables.'
| def get_year_format(self):
| return self.year_format
|
'Return the year for which this view should display data'
| def get_year(self):
| year = self.year
if (year is None):
try:
year = self.kwargs['year']
except KeyError:
try:
year = self.request.GET['year']
except KeyError:
raise Http404(_(u'No year specified'))
return year
|
'Get a month format string in strptime syntax to be used to parse the
month from url variables.'
| def get_month_format(self):
| return self.month_format
|
'Return the month for which this view should display data'
| def get_month(self):
| month = self.month
if (month is None):
try:
month = self.kwargs['month']
except KeyError:
try:
month = self.request.GET['month']
except KeyError:
raise Http404(_(u'No month specified'))
return month
|
'Get the next valid month.'
| def get_next_month(self, date):
| (first_day, last_day) = _month_bounds(date)
next = (last_day + datetime.timedelta(days=1)).replace(day=1)
return _get_next_prev_month(self, next, is_previous=False, use_first_day=True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.