desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Transmit headers to the client, via self._write()'
def send_headers(self):
self.cleanup_headers() self.headers_sent = True if ((not self.origin_server) or self.client_is_modern()): self.send_preamble() self._write(str(self.headers))
'True if \'self.result\' is an instance of \'self.wsgi_file_wrapper\''
def result_is_file(self):
wrapper = self.wsgi_file_wrapper return ((wrapper is not None) and isinstance(self.result, wrapper))
'True if client can accept status and headers'
def client_is_modern(self):
return (self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9')
'Log the \'exc_info\' tuple in the server log Subclasses may override to retarget the output or change its format.'
def log_exception(self, exc_info):
try: from traceback import print_exception stderr = self.get_stderr() print_exception(exc_info[0], exc_info[1], exc_info[2], self.traceback_limit, stderr) stderr.flush() finally: exc_info = None
'Log current error, and send error output to client if possible'
def handle_error(self):
self.log_exception(sys.exc_info()) if (not self.headers_sent): self.result = self.error_output(self.environ, self.start_response) self.finish_response()
'Override server_bind to store the server name.'
def server_bind(self):
try: HTTPServer.server_bind(self) except Exception as e: raise WSGIServerException(e) self.setup_environ()
'Handle a single HTTP request'
def handle(self):
self.raw_requestline = self.rfile.readline() if (not self.parse_request()): return handler = ServerHandler(self.rfile, self.wfile, self.get_stderr(), self.get_environ()) handler.request_handler = self handler.run(self.server.get_app())
'Returns the path to the media file on disk for the given URL. The passed URL is assumed to begin with ADMIN_MEDIA_PREFIX. If the resultant file path is outside the media directory, then a ValueError is raised.'
def file_path(self, url):
relative_url = url[len(self.media_url):] relative_path = urllib.url2pathname(relative_url) return safe_join(self.media_dir, relative_path)
'Populate middleware lists from settings.MIDDLEWARE_CLASSES. Must be called after the environment is fixed (see __call__).'
def load_middleware(self):
from google.appengine._internal.django.conf import settings from google.appengine._internal.django.core import exceptions self._view_middleware = [] self._response_middleware = [] self._exception_middleware = [] request_middleware = [] for middleware_path in settings.MIDDLEWARE_CLASSES: ...
'Returns an HttpResponse object for the given HttpRequest'
def get_response(self, request):
from google.appengine._internal.django.core import exceptions, urlresolvers from google.appengine._internal.django.conf import settings try: urlconf = settings.ROOT_URLCONF urlresolvers.set_urlconf(urlconf) resolver = urlresolvers.RegexURLResolver('^/', urlconf) for middlewar...
'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 google.appengine._internal.django.conf import settings from google.appengine._internal.django.core.mail import mail_admins if settings.DEBUG_PROPAGATE_EXCEPTIONS: raise if settings.DEBUG: from google.appengine._internal.django.views import debug return debug.technical_500_re...
'Helper function to return the traceback as a string'
def _get_traceback(self, exc_info=None):
import traceback return '\n'.join(traceback.format_exception(*(exc_info or sys.exc_info())))
'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
'Populates self._post and self._files'
def _load_post_and_files(self):
if (self.method != 'POST'): (self._post, self._files) = (http.QueryDict('', encoding=self._encoding), datastructures.MultiValueDict()) return if (('content-type' in self._req.headers_in) and self._req.headers_in['content-type'].startswith('multipart')): self._raw_post_data = '' t...
'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
'Write all messages to the stream in a thread-safe way.'
def send_messages(self, email_messages):
if (not email_messages): return self._lock.acquire() try: stream_created = self.open() for message in email_messages: self.stream.write(('%s\n' % message.message().as_string())) self.stream.write(('-' * 79)) self.stream.write('\n') self...
'Return a unique file name.'
def _get_filename(self):
if (self._fname is None): timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S') fname = ('%s-%s.log' % (timestamp, abs(id(self)))) self._fname = os.path.join(self.file_path, fname) return self._fname
'Ensures we have a connection to the email server. Returns whether or not a new connection was required (True or False).'
def open(self):
if self.connection: return False try: self.connection = smtplib.SMTP(self.host, self.port, local_hostname=DNS_NAME.get_fqdn()) if self.use_tls: self.connection.ehlo() self.connection.starttls() self.connection.ehlo() if (self.username and self....
'Closes the connection to the email server.'
def close(self):
try: self.connection.quit() except socket.sslerror: self.connection.close() except: if self.fail_silently: return raise finally: self.connection = None
'Sends one or more EmailMessage objects and returns the number of email messages sent.'
def send_messages(self, email_messages):
if (not email_messages): return self._lock.acquire() try: new_conn_created = self.open() if (not self.connection): return num_sent = 0 for message in email_messages: sent = self._send(message) if sent: num_sent += 1 ...
'A helper method that does the actual sending.'
def _send(self, email_message):
if (not email_message.recipients()): return False from_email = sanitize_address(email_message.from_email, email_message.encoding) recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.recipients()] try: self.connection.sendmail(from_email, recipients, ema...
'Redirect messages to the dummy outbox'
def send_messages(self, messages):
mail.outbox.extend(messages) return len(messages)
'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):
if to: assert (not isinstance(to, basestring)), '"to" argument must be a list or tuple' self.to = list(to) else: self.to = [] if bcc: assert (not isinstance(bcc, basestring)), '"bcc" argument must be a list or tuple' self.bcc ...
'Returns a list of all recipients of the email (includes direct addressees as well as Bcc entries).'
def recipients(self):
return (self.to + self.bcc)
'Sends the email message.'
def send(self, fail_silently=False):
if (not self.recipients()): return 0 return self.get_connection(fail_silently).send_messages([self])
'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)