desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Attaches a file with the given filename and content. The filename can
be omitted and the mimetype is guessed, if not provided.
If the first parameter is a MIMEBase subclass it is inserted directly
into the resulting message attachments.'
| def attach(self, filename=None, content=None, mimetype=None):
| if isinstance(filename, MIMEBase):
assert (content == mimetype == None)
self.attachments.append(filename)
else:
assert (content is not None)
self.attachments.append((filename, content, mimetype))
|
'Attaches a file from the filesystem.'
| def attach_file(self, path, mimetype=None):
| filename = os.path.basename(path)
content = open(path, 'rb').read()
self.attach(filename, content, mimetype)
|
'Converts the content, mimetype pair into a MIME attachment object.'
| def _create_mime_attachment(self, content, mimetype):
| (basetype, subtype) = mimetype.split('/', 1)
if (basetype == 'text'):
encoding = (self.encoding or settings.DEFAULT_CHARSET)
attachment = SafeMIMEText(smart_str(content, encoding), subtype, encoding)
else:
attachment = MIMEBase(basetype, subtype)
attachment.set_payload(conten... |
'Converts the filename, content, mimetype triple into a MIME attachment
object.'
| def _create_attachment(self, filename, content, mimetype=None):
| if (mimetype is None):
(mimetype, _) = mimetypes.guess_type(filename)
if (mimetype is None):
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
attachment = self._create_mime_attachment(content, mimetype)
if filename:
attachment.add_header('Content-Disposition', 'attachment', filena... |
'Initialize a single email message (which can be sent to multiple
recipients).
All strings used to create the message can be unicode strings (or UTF-8
bytestrings). The SafeMIMEText class will handle any necessary encoding
conversions.'
| def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, alternatives=None):
| super(EmailMultiAlternatives, self).__init__(subject, body, from_email, to, bcc, connection, attachments, headers)
self.alternatives = (alternatives or [])
|
'Attach an alternative content representation.'
| def attach_alternative(self, content, mimetype):
| assert (content is not None)
assert (mimetype is not None)
self.alternatives.append((content, mimetype))
|
'Returns the full path of this file.'
| def temporary_file_path(self):
| return self.file.name
|
'Creates a SimpleUploadedFile object from
a dictionary object with the following keys:
- filename
- content-type
- content'
| def from_dict(cls, file_dict):
| return cls(file_dict['filename'], file_dict['content'], file_dict.get('content-type', 'text/plain'))
|
'Read the file and yield chucks of ``chunk_size`` bytes (defaults to
``UploadedFile.DEFAULT_CHUNK_SIZE``).'
| def chunks(self, chunk_size=None):
| if (not chunk_size):
chunk_size = self.DEFAULT_CHUNK_SIZE
if hasattr(self, 'seek'):
self.seek(0)
counter = self.size
while (counter > 0):
(yield self.read(chunk_size))
counter -= chunk_size
|
'Returns ``True`` if you can expect multiple chunks.
NB: If a particular file representation is in memory, subclasses should
always return ``False`` -- there\'s no good reason to read from memory in
chunks.'
| def multiple_chunks(self, chunk_size=None):
| if (not chunk_size):
chunk_size = self.DEFAULT_CHUNK_SIZE
return (self.size > chunk_size)
|
'If ``connection_reset`` is ``True``, Django knows will halt the upload
without consuming the rest of the upload. This will cause the browser to
show a "connection reset" error.'
| def __init__(self, connection_reset=False):
| self.connection_reset = connection_reset
|
'Handle the raw input from the client.
Parameters:
:input_data:
An object that supports reading via .read().
:META:
``request.META``.
:content_length:
The (integer) value of the Content-Length header from the
client.
:boundary: The boundary from the Content-Type header. Be sure to
prepend two \'--\'.'
| def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
| pass
|
'Signal that a new file has been started.
Warning: As with any data from the client, you should not trust
content_length (and sometimes won\'t even get it).'
| def new_file(self, field_name, file_name, content_type, content_length, charset=None):
| self.field_name = field_name
self.file_name = file_name
self.content_type = content_type
self.content_length = content_length
self.charset = charset
|
'Receive data from the streamed upload parser. ``start`` is the position
in the file of the chunk.'
| def receive_data_chunk(self, raw_data, start):
| raise NotImplementedError()
|
'Signal that a file has completed. File size corresponds to the actual
size accumulated by all the chunks.
Subclasses should return a valid ``UploadedFile`` object.'
| def file_complete(self, file_size):
| raise NotImplementedError()
|
'Signal that the upload is complete. Subclasses should perform cleanup
that is necessary for this handler.'
| def upload_complete(self):
| pass
|
'Create the file object to append to as data is coming in.'
| def new_file(self, file_name, *args, **kwargs):
| super(TemporaryFileUploadHandler, self).new_file(file_name, *args, **kwargs)
self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0, self.charset)
|
'Use the content_length to signal whether or not this handler should be in use.'
| def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
| if (content_length > settings.FILE_UPLOAD_MAX_MEMORY_SIZE):
self.activated = False
else:
self.activated = True
|
'Add the data to the StringIO file.'
| def receive_data_chunk(self, raw_data, start):
| if self.activated:
self.file.write(raw_data)
else:
return raw_data
|
'Return a file object if we\'re activated.'
| def file_complete(self, file_size):
| if (not self.activated):
return
self.file.seek(0)
return InMemoryUploadedFile(file=self.file, field_name=self.field_name, name=self.file_name, content_type=self.content_type, size=file_size, charset=self.charset)
|
'Retrieves the specified file from storage, using the optional mixin
class to customize what features are available on the File returned.'
| def open(self, name, mode='rb', mixin=None):
| file = self._open(name, mode)
if mixin:
file.__class__ = type(mixin.__name__, (mixin, file.__class__), {})
return file
|
'Saves new content to the file specified by name. The content should be a
proper File object, ready to be read from the beginning.'
| def save(self, name, content):
| if (name is None):
name = content.name
name = self.get_available_name(name)
name = self._save(name, content)
return force_unicode(name.replace('\\', '/'))
|
'Returns a filename, based on the provided filename, that\'s suitable for
use in the target storage system.'
| def get_valid_name(self, name):
| return get_valid_filename(name)
|
'Returns a filename that\'s free on the target storage system, and
available for new content to be written to.'
| def get_available_name(self, name):
| (dir_name, file_name) = os.path.split(name)
(file_root, file_ext) = os.path.splitext(file_name)
count = itertools.count(1)
while self.exists(name):
name = os.path.join(dir_name, ('%s_%s%s' % (file_root, count.next(), file_ext)))
return name
|
'Returns a local filesystem path where the file can be retrieved using
Python\'s built-in open() function. Storage systems that can\'t be
accessed using open() should *not* implement this method.'
| def path(self, name):
| raise NotImplementedError("This backend doesn't support absolute paths.")
|
'Deletes the specified file from the storage system.'
| def delete(self, name):
| raise NotImplementedError()
|
'Returns True if a file referened by the given name already exists in the
storage system, or False if the name is available for a new file.'
| def exists(self, name):
| raise NotImplementedError()
|
'Lists the contents of the specified path, returning a 2-tuple of lists;
the first item being directories, the second item being files.'
| def listdir(self, path):
| raise NotImplementedError()
|
'Returns the total size, in bytes, of the file specified by name.'
| def size(self, name):
| raise NotImplementedError()
|
'Returns an absolute URL where the file\'s contents can be accessed
directly by a Web browser.'
| def url(self, name):
| raise NotImplementedError()
|
'Adds the prefix string to a string-based callback.'
| def add_prefix(self, prefix):
| if ((not prefix) or (not hasattr(self, '_callback_str'))):
return
self._callback_str = ((prefix + '.') + self._callback_str)
|
'Validates the given 1-based page number.'
| def validate_number(self, number):
| try:
number = int(number)
except ValueError:
raise PageNotAnInteger('That page number is not an integer')
if (number < 1):
raise EmptyPage('That page number is less than 1')
if (number > self.num_pages):
if ((number == 1) and self.allow... |
'Returns a Page object for the given 1-based page number.'
| def page(self, number):
| number = self.validate_number(number)
bottom = ((number - 1) * self.per_page)
top = (bottom + self.per_page)
if ((top + self.orphans) >= self.count):
top = self.count
return Page(self.object_list[bottom:top], number, self)
|
'Returns the total number of objects, across all pages.'
| def _get_count(self):
| if (self._count is None):
try:
self._count = self.object_list.count()
except (AttributeError, TypeError):
self._count = len(self.object_list)
return self._count
|
'Returns the total number of pages.'
| def _get_num_pages(self):
| if (self._num_pages is None):
if ((self.count == 0) and (not self.allow_empty_first_page)):
self._num_pages = 0
else:
hits = max(1, (self.count - self.orphans))
self._num_pages = int(ceil((hits / float(self.per_page))))
return self._num_pages
|
'Returns a 1-based range of pages for iterating through within
a template for loop.'
| def _get_page_range(self):
| return range(1, (self.num_pages + 1))
|
'Returns the 1-based index of the first object on this page,
relative to total objects in the paginator.'
| def start_index(self):
| if (self.paginator.count == 0):
return 0
return ((self.paginator.per_page * (self.number - 1)) + 1)
|
'Returns the 1-based index of the last object on this page,
relative to total objects found (hits).'
| def end_index(self):
| if (self.number == self.paginator.num_pages):
return self.paginator.count
return (self.number * self.paginator.per_page)
|
'Serialize a queryset.'
| def serialize(self, queryset, **options):
| self.options = options
self.stream = options.pop('stream', StringIO())
self.selected_fields = options.pop('fields', None)
self.use_natural_keys = options.pop('use_natural_keys', False)
self.start_serialization()
for obj in queryset:
self.start_object(obj)
for field in obj._meta.l... |
'Convert a field\'s value to a string.'
| def get_string_value(self, obj, field):
| return smart_unicode(field.value_to_string(obj))
|
'Called when serializing of the queryset starts.'
| def start_serialization(self):
| raise NotImplementedError
|
'Called when serializing of the queryset ends.'
| def end_serialization(self):
| pass
|
'Called when serializing of an object starts.'
| def start_object(self, obj):
| raise NotImplementedError
|
'Called when serializing of an object ends.'
| def end_object(self, obj):
| pass
|
'Called to handle each individual (non-relational) field on an object.'
| def handle_field(self, obj, field):
| raise NotImplementedError
|
'Called to handle a ForeignKey field.'
| def handle_fk_field(self, obj, field):
| raise NotImplementedError
|
'Called to handle a ManyToManyField.'
| def handle_m2m_field(self, obj, field):
| raise NotImplementedError
|
'Return the fully serialized queryset (or None if the output stream is
not seekable).'
| def getvalue(self):
| if callable(getattr(self.stream, 'getvalue', None)):
return self.stream.getvalue()
|
'Init this serializer given a stream or a string'
| def __init__(self, stream_or_string, **options):
| self.options = options
if isinstance(stream_or_string, basestring):
self.stream = StringIO(stream_or_string)
else:
self.stream = stream_or_string
models.get_apps()
|
'Iteration iterface -- return the next item in the stream'
| def next(self):
| raise NotImplementedError
|
'Start serialization -- open the XML document and the root element.'
| def start_serialization(self):
| self.xml = SimplerXMLGenerator(self.stream, self.options.get('encoding', settings.DEFAULT_CHARSET))
self.xml.startDocument()
self.xml.startElement('django-objects', {'version': '1.0'})
|
'End serialization -- end the document.'
| def end_serialization(self):
| self.indent(0)
self.xml.endElement('django-objects')
self.xml.endDocument()
|
'Called as each object is handled.'
| def start_object(self, obj):
| if (not hasattr(obj, '_meta')):
raise base.SerializationError(('Non-model object (%s) encountered during serialization' % type(obj)))
self.indent(1)
obj_pk = obj._get_pk_val()
if (obj_pk is None):
attrs = {'model': smart_unicode(obj._meta)}
else:
attrs = {'pk':... |
'Called after handling all fields for an object.'
| def end_object(self, obj):
| self.indent(1)
self.xml.endElement('object')
|
'Called to handle each field on an object (except for ForeignKeys and
ManyToManyFields)'
| def handle_field(self, obj, field):
| self.indent(2)
self.xml.startElement('field', {'name': field.name, 'type': field.get_internal_type()})
if (getattr(obj, field.name) is not None):
self.xml.characters(field.value_to_string(obj))
else:
self.xml.addQuickElement('None')
self.xml.endElement('field')
|
'Called to handle a ForeignKey (we need to treat them slightly
differently from regular fields).'
| def handle_fk_field(self, obj, field):
| self._start_relational_field(field)
related = getattr(obj, field.name)
if (related is not None):
if (self.use_natural_keys and hasattr(related, 'natural_key')):
related = related.natural_key()
for key_value in related:
self.xml.startElement('natural', {})
... |
'Called to handle a ManyToManyField. Related objects are only
serialized as references to the object\'s PK (i.e. the related *data*
is not dumped, just the relation).'
| def handle_m2m_field(self, obj, field):
| if field.rel.through._meta.auto_created:
self._start_relational_field(field)
if (self.use_natural_keys and hasattr(field.rel.to, 'natural_key')):
def handle_m2m(value):
natural = value.natural_key()
self.xml.startElement('object', {})
for k... |
'Helper to output the <field> element for relational fields'
| def _start_relational_field(self, field):
| self.indent(2)
self.xml.startElement('field', {'name': field.name, 'rel': field.rel.__class__.__name__, 'to': smart_unicode(field.rel.to._meta)})
|
'Convert an <object> node to a DeserializedObject.'
| def _handle_object(self, node):
| Model = self._get_model_from_node(node, 'model')
if node.hasAttribute('pk'):
pk = node.getAttribute('pk')
else:
pk = None
data = {Model._meta.pk.attname: Model._meta.pk.to_python(pk)}
m2m_data = {}
for field_node in node.getElementsByTagName('field'):
field_name = field_n... |
'Handle a <field> node for a ForeignKey'
| def _handle_fk_field_node(self, node, field):
| if node.getElementsByTagName('None'):
return None
elif hasattr(field.rel.to._default_manager, 'get_by_natural_key'):
keys = node.getElementsByTagName('natural')
if keys:
field_value = [getInnerText(k).strip() for k in keys]
obj = field.rel.to._default_manager.db_m... |
'Handle a <field> node for a ManyToManyField.'
| def _handle_m2m_field_node(self, node, field):
| if hasattr(field.rel.to._default_manager, 'get_by_natural_key'):
def m2m_convert(n):
keys = n.getElementsByTagName('natural')
if keys:
field_value = [getInnerText(k).strip() for k in keys]
obj_pk = field.rel.to._default_manager.db_manager(self.db).get_... |
'Helper to look up a model from a <object model=...> or a <field
rel=... to=...> node.'
| def _get_model_from_node(self, node, attr):
| model_identifier = node.getAttribute(attr)
if (not model_identifier):
raise base.DeserializationError(("<%s> node is missing the required '%s' attribute" % (node.nodeName, attr)))
try:
Model = models.get_model(*model_identifier.split('.'))
except TypeError:
M... |
'Set a value in the cache if the key does not already exist. If
timeout is given, that timeout will be used for the key; otherwise
the default cache timeout will be used.
Returns True if the value was stored, False otherwise.'
| def add(self, key, value, timeout=None):
| raise NotImplementedError
|
'Fetch a given key from the cache. If the key does not exist, return
default, which itself defaults to None.'
| def get(self, key, default=None):
| raise NotImplementedError
|
'Set a value in the cache. If timeout is given, that timeout will be
used for the key; otherwise the default cache timeout will be used.'
| def set(self, key, value, timeout=None):
| raise NotImplementedError
|
'Delete a key from the cache, failing silently.'
| def delete(self, key):
| raise NotImplementedError
|
'Fetch a bunch of keys from the cache. For certain backends (memcached,
pgsql) this can be *much* faster when fetching multiple values.
Returns a dict mapping each key in keys to its value. If the given
key is missing, it will be missing from the response dict.'
| def get_many(self, keys):
| d = {}
for k in keys:
val = self.get(k)
if (val is not None):
d[k] = val
return d
|
'Returns True if the key is in the cache and has not expired.'
| def has_key(self, key):
| return (self.get(key) is not None)
|
'Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.'
| def incr(self, key, delta=1):
| if (key not in self):
raise ValueError(("Key '%s' not found" % key))
new_value = (self.get(key) + delta)
self.set(key, new_value)
return new_value
|
'Subtract delta from value in the cache. If the key does not exist, raise
a ValueError exception.'
| def decr(self, key, delta=1):
| return self.incr(key, (- delta))
|
'Returns True if the key is in the cache and has not expired.'
| def __contains__(self, key):
| return self.has_key(key)
|
'Set a bunch of values in the cache at once from a dict of key/value
pairs. For certain backends (memcached), this is much more efficient
than calling set() multiple times.
If timeout is given, that timeout will be used for the key; otherwise
the default cache timeout will be used.'
| def set_many(self, data, timeout=None):
| for (key, value) in data.items():
self.set(key, value, timeout)
|
'Set a bunch of values in the cache at once. For certain backends
(memcached), this is much more efficient than calling delete() multiple
times.'
| def delete_many(self, keys):
| for key in keys:
self.delete(key)
|
'Remove *all* values from the cache at once.'
| def clear(self):
| raise NotImplementedError
|
'Warn about keys that would not be portable to the memcached
backend. This encourages (but does not force) writing backend-portable
cache code.'
| def validate_key(self, key):
| if (len(key) > MEMCACHE_MAX_KEY_LENGTH):
warnings.warn(('Cache key will cause errors if used with memcached: %s (longer than %s)' % (key, MEMCACHE_MAX_KEY_LENGTH)), CacheKeyWarning)
for char in key:
if ((ord(char) < 33) or (ord(char) == 127)):
warn... |
'Convert the filename into an md5 string. We\'ll turn the first couple
bits of the path into directory prefixes to be nice to filesystems
that have problems with large numbers of files in a directory.
Thus, a cache key of "foo" gets turnned into a file named
``{cache-dir}ac/bd/18db4cc2f85cedef654fccc4a4d8``.'
| def _key_to_file(self, key):
| path = md5_constructor(key.encode('utf-8')).hexdigest()
path = os.path.join(path[:2], path[2:4], path[4:])
return os.path.join(self._dir, path)
|
'Memcached deals with long (> 30 days) timeouts in a special
way. Call this function to obtain a safe value for your timeout.'
| def _get_memcache_timeout(self, timeout):
| timeout = (timeout or self.default_timeout)
if (timeout > 2592000):
timeout += int(time.time())
return timeout
|
'Validates that the input matches the regular expression.'
| def __call__(self, value):
| if (not self.regex.search(smart_unicode(value))):
raise ValidationError(self.message, code=self.code)
|
'Create new instance or return current instance
Basically this method of construction allows us to
short-circuit creation of references to already-
referenced instance methods. The key corresponding
to the target is calculated, and if there is already
an existing reference, that is returned, with its
deletionMethods a... | def __new__(cls, target, onDelete=None, *arguments, **named):
| key = cls.calculateKey(target)
current = cls._allInstances.get(key)
if (current is not None):
current.deletionMethods.append(onDelete)
return current
else:
base = super(BoundMethodWeakref, cls).__new__(cls)
cls._allInstances[key] = base
base.__init__(target, onDel... |
'Return a weak-reference-like instance for a bound method
target -- the instance-method target for the weak
reference, must have im_self and im_func attributes
and be reconstructable via:
target.im_func.__get__( target.im_self )
which is true of built-in instance methods.
onDelete -- optional callback which will be cal... | def __init__(self, target, onDelete=None):
| def remove(weak, self=self):
'Set self.isDead to true when method or instance is destroyed'
methods = self.deletionMethods[:]
del self.deletionMethods[:]
try:
del self.__class__._allInstances[self.key]
except KeyError:
pass
... |
'Calculate the reference key for this reference
Currently this is a two-tuple of the id()\'s of the
target object and the target function respectively.'
| def calculateKey(cls, target):
| return (id(target.im_self), id(target.im_func))
|
'Give a friendly representation of the object'
| def __str__(self):
| return ('%s( %s.%s )' % (self.__class__.__name__, self.selfName, self.funcName))
|
'Whether we are still a valid reference'
| def __nonzero__(self):
| return (self() is not None)
|
'Compare with another reference'
| def __cmp__(self, other):
| if (not isinstance(other, self.__class__)):
return cmp(self.__class__, type(other))
return cmp(self.key, other.key)
|
'Return a strong reference to the bound method
If the target cannot be retrieved, then will
return None, otherwise returns a bound instance
method for our object and function.
Note:
You may call this method any number of times,
as it does not invalidate the reference.'
| def __call__(self):
| target = self.weakSelf()
if (target is not None):
function = self.weakFunc()
if (function is not None):
return function.__get__(target)
return None
|
'Return a weak-reference-like instance for a bound method
target -- the instance-method target for the weak
reference, must have im_self and im_func attributes
and be reconstructable via:
target.im_func.__get__( target.im_self )
which is true of built-in instance methods.
onDelete -- optional callback which will be cal... | def __init__(self, target, onDelete=None):
| assert (getattr(target.im_self, target.__name__) == target), ("method %s isn't available as the attribute %s of %s" % (target, target.__name__, target.im_self))
super(BoundNonDescriptorMethodWeakref, self).__init__(target, onDelete)
|
'Return a strong reference to the bound method
If the target cannot be retrieved, then will
return None, otherwise returns a bound instance
method for our object and function.
Note:
You may call this method any number of times,
as it does not invalidate the reference.'
| def __call__(self):
| target = self.weakSelf()
if (target is not None):
function = self.weakFunc()
if (function is not None):
return getattr(target, function.__name__)
return None
|
'Create a new signal.
providing_args
A list of the arguments this signal can pass along in a send() call.'
| def __init__(self, providing_args=None):
| self.receivers = []
if (providing_args is None):
providing_args = []
self.providing_args = set(providing_args)
self.lock = threading.Lock()
|
'Connect receiver to sender for signal.
Arguments:
receiver
A function or an instance method which is to receive signals.
Receivers must be hashable objects.
If weak is True, then receiver must be weak-referencable (more
precisely saferef.safeRef() must be able to create a reference
to the receiver).
Receivers must be ... | def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
| from django.conf import settings
if settings.DEBUG:
import inspect
assert callable(receiver), 'Signal receivers must be callable.'
try:
argspec = inspect.getargspec(receiver)
except TypeError:
try:
argspec = inspect.getargspec(r... |
'Disconnect receiver from sender for signal.
If weak references are used, disconnect need not be called. The receiver
will be remove from dispatch automatically.
Arguments:
receiver
The registered receiver to disconnect. May be none if
dispatch_uid is specified.
sender
The registered sender to disconnect
weak
The weakr... | def disconnect(self, receiver=None, sender=None, weak=True, dispatch_uid=None):
| if dispatch_uid:
lookup_key = (dispatch_uid, _make_id(sender))
else:
lookup_key = (_make_id(receiver), _make_id(sender))
self.lock.acquire()
try:
for index in xrange(len(self.receivers)):
(r_key, _) = self.receivers[index]
if (r_key == lookup_key):
... |
'Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop, so it is quite possible to not have all
receivers called if a raises an error.
Arguments:
sender
The sender of the signal Either a specific object or None.
named
N... | def send(self, sender, **named):
| responses = []
if (not self.receivers):
return responses
for receiver in self._live_receivers(_make_id(sender)):
response = receiver(signal=self, sender=sender, **named)
responses.append((receiver, response))
return responses
|
'Send signal from sender to all connected receivers catching errors.
Arguments:
sender
The sender of the signal. Can be any python object (normally one
registered with a connect if you actually want something to
occur).
named
Named arguments which will be passed to receivers. These
arguments must be a subset of the arg... | def send_robust(self, sender, **named):
| responses = []
if (not self.receivers):
return responses
for receiver in self._live_receivers(_make_id(sender)):
try:
response = receiver(signal=self, sender=sender, **named)
except Exception as err:
responses.append((receiver, err))
else:
... |
'Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only
live receivers.'
| def _live_receivers(self, senderkey):
| none_senderkey = _make_id(None)
receivers = []
for ((receiverkey, r_senderkey), receiver) in self.receivers:
if ((r_senderkey == none_senderkey) or (r_senderkey == senderkey)):
if isinstance(receiver, WEAKREF_TYPES):
receiver = receiver()
if (receiver is n... |
'Remove dead receivers from connections.'
| def _remove_receiver(self, receiver):
| self.lock.acquire()
try:
to_remove = []
for (key, connected_receiver) in self.receivers:
if (connected_receiver == receiver):
to_remove.append(key)
for key in to_remove:
last_idx = (len(self.receivers) - 1)
for (idx, (r_key, _)) in enum... |
'Creates some methods once self._meta has been populated.'
| def _prepare(cls):
| opts = cls._meta
opts._prepare(cls)
if opts.order_with_respect_to:
cls.get_next_in_order = curry(cls._get_next_or_previous_in_order, is_next=True)
cls.get_previous_in_order = curry(cls._get_next_or_previous_in_order, is_next=False)
def make_foreign_order_accessors(field, model, cls):... |
'Provide pickling support. Normally, this just dispatches to Python\'s
standard handling. However, for models with deferred field loading, we
need to do things manually, as they\'re dynamically created classes and
only module-level classes can be pickled by the default path.'
| def __reduce__(self):
| data = self.__dict__
model = self.__class__
defers = []
pk_val = None
if self._deferred:
from django.db.models.query_utils import deferred_class_factory
factory = deferred_class_factory
for field in self._meta.fields:
if isinstance(self.__class__.__dict__.get(fiel... |
'Returns the value of the field name for this instance. If the field is
a foreign key, returns the id value, instead of the object. If there\'s
no Field object with this name on the model, the model attribute\'s
value is returned directly.
Used to serialize a field\'s value (in the serializer, or form output,
for examp... | def serializable_value(self, field_name):
| try:
field = self._meta.get_field_by_name(field_name)[0]
except FieldDoesNotExist:
return getattr(self, field_name)
return getattr(self, field.attname)
|
'Saves the current instance. Override this in a subclass if you want to
control the saving process.
The \'force_insert\' and \'force_update\' parameters can be used to insist
that the "save" must be an SQL insert or update (or equivalent for
non-SQL backends), respectively. Normally, they should not be set.'
| def save(self, force_insert=False, force_update=False, using=None):
| if (force_insert and force_update):
raise ValueError('Cannot force both insert and updating in model saving.')
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
|
'Does the heavy-lifting involved in saving. Subclasses shouldn\'t need to
override this method. It\'s separate from save() in order to hide the
need for overrides of save() to pass around internal-only parameters
(\'raw\', \'cls\', and \'origin\').'
| def save_base(self, raw=False, cls=None, origin=None, force_insert=False, force_update=False, using=None):
| using = (using or router.db_for_write(self.__class__, instance=self))
connection = connections[using]
assert (not (force_insert and force_update))
if (cls is None):
cls = self.__class__
meta = cls._meta
if (not meta.proxy):
origin = cls
else:
meta = cls._m... |
'Recursively populates seen_objs with all objects related to this
object.
When done, seen_objs.items() will be in the format:
[(model_class, {pk_val: obj, pk_val: obj, ...}),
(model_class, {pk_val: obj, pk_val: obj, ...}), ...]'
| def _collect_sub_objects(self, seen_objs, parent=None, nullable=False):
| pk_val = self._get_pk_val()
if seen_objs.add(self.__class__, pk_val, self, type(parent), parent, nullable):
return
for related in self._meta.get_all_related_objects():
rel_opts_name = related.get_accessor_name()
if (not related.field.rel.multiple):
try:
su... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.