desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Register the class implementing this config, so we only add it once. Args: parsed_config: The JSON object with the API configuration being added. Returns: True if the class has been registered and it\'s fine to add this configuration. False if this configuration shouldn\'t be added.'
def __register_class(self, parsed_config):
methods = parsed_config.get('methods') if (not methods): return True service_class = None for method in methods.itervalues(): rosy_method = method.get('rosyMethod') if (rosy_method and ('.' in rosy_method)): method_class = rosy_method.split('.', 1)[0] if (...
'Register all methods from the given api config file. Methods are stored in a map from method_name to rosyMethod, the name of the ProtoRPC method to be called on the backend. If no rosyMethod was specified the value will be None. Args: parsed_config: The JSON object with the API configuration being added.'
def __register_methods(self, parsed_config):
methods = parsed_config.get('methods') if (not methods): return for (method_name, method) in methods.iteritems(): self.__api_methods[method_name] = method.get('rosyMethod')
'Looks an API method up by name to find the backend method to call. Args: api_method_name: Name of the method in the API that was called. Returns: Name of the ProtoRPC method called on the backend, or None if not found.'
def lookup_api_method(self, api_method_name):
return self.__api_methods.get(api_method_name)
'Return a list of all API configration specs as registered above.'
def all_api_configs(self):
return list(self.__api_configs)
'Create a new BackendService implementation. Args: api_config_registry: ApiConfigRegistry to register and look up configs. app_revision: string containing the current app revision.'
def __init__(self, api_config_registry, app_revision):
self.__api_config_registry = api_config_registry self.__app_revision = app_revision
'Override definition_name so that it is not BackendServiceImpl.'
@staticmethod def definition_name():
return api_backend.BackendService.definition_name()
'Return a list of active APIs and their configuration files. Args: request: A request which may contain an app revision Returns: ApiConfigList: A list of API config strings'
def getApiConfigs(self, request):
if (request.appRevision and (request.appRevision != self.__app_revision)): raise api_exceptions.BadRequestException(message=('API backend app revision %s not the same as expected %s' % (self.__app_revision, request.appRevision))) configs = self.__api_config_registry.all_api...
'Write a log message from the Swarm FE to the log. Args: request: A log message request. Returns: Void message.'
def logMessages(self, request):
Level = api_backend.LogMessagesRequest.LogMessage.Level log = logging.getLogger(__name__) for message in request.messages: level = (message.level if (message.level is not None) else Level.info) record = logging.LogRecord(name=__name__, level=level.number, pathname='', lineno='', msg=message....
'Constructor. Args: query_string: Properly formatted GQL query string. model_class: Model class from which entities are constructed. *args: Positional arguments used to bind numeric references in the query. **kwds: Dictionary-based arguments for named references.'
def __init__(self, query_string, model_class, *args, **kwds):
from google.appengine.ext import gql app = kwds.pop('_app', None) self._proto_query = gql.GQL(query_string, _app=app, namespace='') super(db.GqlQuery, self).__init__(model_class) self.bind(*args, **kwds)
'Constructor for wrapping blobstore entity. The constructor should not be used outside this package and tests. Args: entity: Datastore entity that represents the blob reference.'
def __init__(self, entity_or_blob_key, _values=None):
if isinstance(entity_or_blob_key, datastore.Entity): self.__entity = entity_or_blob_key self.__key = BlobKey(entity_or_blob_key.key().name()) elif isinstance(entity_or_blob_key, BlobKey): self.__entity = _values self.__key = entity_or_blob_key else: raise TypeError('M...
'Convert entity to BlobInfo. This method is required for compatibility with the current db.py query mechanism but will be removed in the future. DO NOT USE.'
@classmethod def from_entity(cls, entity):
return BlobInfo(entity)
'Set of properties that belong to BlobInfo. This method is required for compatibility with the current db.py query mechanism but will be removed in the future. DO NOT USE.'
@classmethod def properties(cls):
return set(cls._all_properties)
'Get a BlobInfo value, loading entity if necessary. This method allows lazy loading of the underlying datastore entity. It should never be invoked directly. Args: name: Name of property to get value for. Returns: Value of BlobInfo property from entity.'
def __get_value(self, name):
if (self.__entity is None): self.__entity = datastore.Get(datastore_types.Key.from_path(self.kind(), str(self.__key), namespace='')) try: return self.__entity[name] except KeyError: raise AttributeError(name)
'Get key for blob. Returns: BlobKey instance that identifies this blob.'
def key(self):
return self.__key
'Permanently delete blob from Blobstore.'
def delete(self):
delete(self.key())
'Returns a BlobReader for this blob. Args: *args, **kwargs: Passed to BlobReader constructor. Returns: A BlobReader instance.'
def open(self, *args, **kwargs):
return BlobReader(self, *args, **kwargs)
'Retrieve BlobInfo by key or list of keys. Args: blob_keys: A key or a list of keys. Keys may be instances of str, unicode and BlobKey. Returns: A BlobInfo instance associated with provided key or a list of BlobInfo instances if a list of keys was provided. Keys that are not found in Blobstore return None as their va...
@classmethod def get(cls, blob_keys):
blob_keys = cls.__normalize_and_convert_keys(blob_keys) try: entities = datastore.Get(blob_keys) except datastore_errors.EntityNotFoundError: return None if isinstance(entities, datastore.Entity): return BlobInfo(entities) else: references = [] for entity in e...
'Get query for all Blobs associated with application. Returns: A db.Query object querying over BlobInfo\'s datastore kind.'
@classmethod def all(cls):
return db.Query(model_class=cls, namespace='')
'Returns a query using GQL query string. See appengine/ext/gql for more information about GQL. Args: query_string: Properly formatted GQL query string with the \'SELECT * FROM <entity>\' part omitted *args: rest of the positional arguments used to bind numeric references in the query. **kwds: dictionary-based arguments...
@classmethod def gql(cls, query_string, *args, **kwds):
return _GqlQuery(('SELECT * FROM %s %s' % (cls.kind(), query_string)), cls, *args, **kwds)
'Get the entity kind for the BlobInfo. This method is required for compatibility with the current db.py query mechanism but will be removed in the future. DO NOT USE.'
@classmethod def kind(self):
return BLOB_INFO_KIND
'Normalize and convert all keys to BlobKey type. This method is based on datastore.NormalizeAndTypeCheck(). Args: keys: A single key or a list/tuple of keys. Keys may be a string or BlobKey Returns: Single key or list with all strings replaced by BlobKey instances.'
@classmethod def __normalize_and_convert_keys(cls, keys):
if isinstance(keys, (list, tuple)): multiple = True keys = list(keys) else: multiple = False keys = [keys] for (index, key) in enumerate(keys): if (not isinstance(key, (basestring, BlobKey))): raise datastore_errors.BadArgumentError(('Expected str or...
'Translate model property to datastore value.'
def get_value_for_datastore(self, model_instance):
blob_info = super(BlobReferenceProperty, self).get_value_for_datastore(model_instance) if (blob_info is None): return None return blob_info.key()
'Translate datastore value to BlobInfo.'
def make_value_from_datastore(self, value):
if (value is None): return None return BlobInfo(value)
'Validate that assigned value is BlobInfo. Automatically converts from strings and BlobKey instances.'
def validate(self, value):
if isinstance(value, basestring): value = BlobInfo(BlobKey(value)) elif isinstance(value, BlobKey): value = BlobInfo(value) return super(BlobReferenceProperty, self).validate(value)
'Constructor. Args: blob: The blob key, blob info, or string blob key to read from. buffer_size: The minimum size to fetch chunks of data from blobstore. position: The initial position in the file. Raises: ValueError if a blob key, blob info or string blob key is not supplied.'
def __init__(self, blob, buffer_size=131072, position=0):
if (not blob): raise ValueError('A BlobKey, BlobInfo or string is required.') if hasattr(blob, 'key'): self.__blob_key = blob.key() self.__blob_info = blob else: self.__blob_key = blob self.__blob_info = None self.__buffer_size = buffer_size ...
'Returns a file iterator for this BlobReader.'
def __iter__(self):
return self
'Returns the serialized state for this BlobReader.'
def __getstate__(self):
return (self.__blob_key, self.__buffer_size, self.__position)
'Restores pickled state for this BlobReader.'
def __setstate__(self, state):
self.__init__(*state)
'Close the file. A closed file cannot be read or written any more. Any operation which requires that the file be open will raise a ValueError after the file has been closed. Calling close() more than once is allowed.'
def close(self):
self.__blob_key = None
'Returns the next line from the file. Returns: A string, terminted by . The last line may not be terminated by If EOF is reached, an empty string will be returned.'
def next(self):
line = self.readline() if (not line): raise StopIteration return line
'Reads at most size bytes from the buffer. Args: size: Number of bytes to read, or negative to read the entire buffer. Returns: Tuple (data, size): data: The bytes read from the buffer. size: The remaining unread byte count. Negative when size is negative. Thus when remaining size != 0, the calling method may choose to...
def __read_from_buffer(self, size):
if (not self.__blob_key): raise ValueError('File is closed') if (size < 0): end_pos = len(self.__buffer) else: end_pos = (self.__buffer_position + size) data = self.__buffer[self.__buffer_position:end_pos] data_length = len(data) size -= data_length self.__posit...
'Fills the internal buffer. Args: size: Number of bytes to read. Will be clamped to [self.__buffer_size, MAX_BLOB_FETCH_SIZE].'
def __fill_buffer(self, size=0):
read_size = min(max(size, self.__buffer_size), MAX_BLOB_FETCH_SIZE) self.__buffer = fetch_data(self.__blob_key, self.__position, ((self.__position + read_size) - 1)) self.__buffer_position = 0 self.__eof = (len(self.__buffer) < read_size)
'Read at most size bytes from the file. Fewer bytes are read if the read hits EOF before obtaining size bytes. If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. Calling read() witho...
def read(self, size=(-1)):
data_list = [] while True: (data, size) = self.__read_from_buffer(size) data_list.append(data) if ((size == 0) or self.__eof): return ''.join(data_list) self.__fill_buffer(size)
'Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is r...
def readline(self, size=(-1)):
data_list = [] while True: if (size < 0): end_pos = len(self.__buffer) else: end_pos = (self.__buffer_position + size) newline_pos = self.__buffer.find('\n', self.__buffer_position, end_pos) if (newline_pos != (-1)): data_list.append(self.__rea...
'Read until EOF using readline() and return a list of lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Args: sizehint: A hint as to the maximum number of bytes...
def readlines(self, sizehint=None):
lines = [] while ((sizehint is None) or (sizehint > 0)): line = self.readline() if sizehint: sizehint -= len(line) if (not line): break lines.append(line) return lines
'Set the file\'s current position, like stdio\'s fseek(). The whence argument is optional and defaults to os.SEEK_SET or 0 (absolute file positioning); other values are os.SEEK_CUR or 1 (seek relative to the current position) and os.SEEK_END or 2 (seek relative to the file\'s end). Args: offset: The relative offset to ...
def seek(self, offset, whence=SEEK_SET):
if (whence == BlobReader.SEEK_CUR): offset = (self.__position + offset) elif (whence == BlobReader.SEEK_END): offset = (self.blob_info.size + offset) self.__buffer = '' self.__buffer_position = 0 self.__position = offset self.__eof = False
'Return the file\'s current position, like stdio\'s ftell().'
def tell(self):
return self.__position
'Returns the BlobInfo for this file.'
@property def blob_info(self):
if (not self.__blob_info): self.__blob_info = BlobInfo.get(self.__blob_key) return self.__blob_info
'Returns True if this file is closed, False otherwise.'
@property def closed(self):
return (self.__blob_key is None)
'Fetches the BlobMigrationRecord for the given blob key. Args: old_blob_key: The blob key used in the previous app. Returns: A instance of blobstore.BlobMigrationRecord or None'
@classmethod def get_by_blob_key(cls, old_blob_key):
return cls.get_by_key_name(str(old_blob_key))
'Looks up the new key for a blob. Args: old_blob_key: The original blob key. Returns: The blobstore.BlobKey of the migrated blob.'
@classmethod def get_new_blob_key(cls, old_blob_key):
record = cls.get_by_blob_key(old_blob_key) if record: return record.new_blob_ref.key()
'Handler to redirect all /_ah/admin.* requests to Admin Console.'
def get(self):
app_id = self.request.environ.get(APPLICATION_ID_PARAM) if (not app_id): logging.error('Could not get application id; generic redirect.') self.redirect(APPENGINE_URL) return server = self.request.environ.get(SERVER_NAME_PARAM) if (not server): logging.wa...
'Sets the target and the args to be provided to this background request. Args: target: A callable for the background thread to execute. args: A tuple of positional args to be passed to target. kwargs: A dict of keyword args to be passed to target. Returns: The thread ID of the thread servicing this background request.'...
def ProvideCallable(self, target, args, kwargs):
with self._ready_condition: self._target = target self._args = args self._kwargs = kwargs self._callable_ready = True self._ready_condition.notify() while (not self._thread_id_ready): self._ready_condition.wait() return self._thread_id
'Sets the thread ID and returns the callable and args for this request. This will block until the request details have been set. Returns: A tuple (target, args, kwargs) where target: A callable for the background thread to execute. args: A tuple of positional args to be passed to target. kwargs: A dict of keyword args ...
def WaitForCallable(self):
with self._ready_condition: self._thread_id = thread.get_ident() self._thread_id_ready = True self._ready_condition.notify() while (not self._callable_ready): self._ready_condition.wait() return (self._target, self._args, self._kwargs)
'Enqueues a new background thread request for a certain request ID. Args: request_id: A str containing the request ID for this background thread. target: A callable for the background thread to execute. args: A tuple of positional args to be passed to target. kwargs: A dict of keyword args to be passed to target. Retur...
def EnqueueBackgroundThread(self, request_id, target, args, kwargs):
request = self._GetOrAddRequest(request_id) return request.ProvideCallable(target, args, kwargs)
'Runs the callable enqueued for the specified request ID.'
def RunBackgroundThread(self, request_id):
request = self._GetOrAddRequest(request_id) (target, args, kwargs) = request.WaitForCallable() self._RemoveRequest(request_id) target(*args, **kwargs)
'Creates a single WSGI request. Creates a request for handler_name in the form \'path.to.handler\' for url with the environment contained in environ. Args: environ: A dict containing the environ for this request (e.g. like from os.environ). handler_name: A str containing the user-specified handler to use for this reque...
def __init__(self, environ, handler_name, url, post_data, error):
self._handler = handler_name self._status = 500 self._response_headers = [] self._started_handling = False self._body = [] self._written_body = [] environ['wsgi.multiprocess'] = True environ['wsgi.run_once'] = False environ['wsgi.version'] = (1, 0) environ.setdefault('wsgi.multit...
'Writes some body_data to the response. Args: body_data: data to be written. Raises: InvalidResponseError: body_data is not a str.'
def _Write(self, body_data):
if (not isinstance(body_data, str)): raise InvalidResponseError(('body_data must be a str, got %r' % _GetTypeName(body_data))) self._written_body.append(body_data)
'A PEP 333 start_response callable. Implements the start_response behaviour of PEP 333. Sets the status code and response headers as provided. If exc_info is not None, then the previously provided status and response headers are replaced; this implementation buffers the complete response so valid use of exc_info never ...
def _StartResponse(self, status, response_headers, exc_info=None):
if (not isinstance(status, str)): raise InvalidResponseError(('status must be a str, got %r (%r)' % (_GetTypeName(status), status))) if (not status): raise InvalidResponseError('status must not be empty') if (not isinstance(response_headers, list)): r...
'Handles the request represented by the WsgiRequest object. Loads the handler from the handler name provided. Calls the handler with the environ. Any exceptions in loading the user handler and executing it are caught and logged. Returns: A dict containing: error: App Engine error code. 0 for OK, 1 for error. response_c...
def Handle(self):
try: handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) except runtime.DeadlineExceededError: exc_info = sys.exc_info() try: logging.error('', exc_info=exc_info) except runtime.DeadlineExceededError: logging.exception('Deadline exception ...
'Find and return a Python object with name handler_name. Find and return a Python object specified by self._handler. Packages and modules are imported as necessary. If successful, the filename of the module is inserted into environ with key \'PATH_TRANSLATED\' if it has one. Returns: A Python object. Raises: ImportErro...
def _LoadHandler(self):
path = self._handler.split('.') handler = __import__(path[0]) is_parent_package = True cumulative_path = path[0] for name in path[1:]: if hasattr(handler, '__file__'): self._environ['PATH_TRANSLATED'] = handler.__file__ is_parent_package = (is_parent_package and hasattr(h...
'Resets the error stream and environment for this request.'
def Reset(self):
self.errors = _sys_stderr self.environ = {}
'Returns a callable that will install the environment in another thread. Returns: A callable that will duplicate the request environment of this thread in another thread that calls it.'
def CloneRequestEnvironment(self):
errors = self.errors environ = dict(self.environ) return (lambda : self.Init(errors, environ))
'Clears the thread locals.'
def Clear(self):
self.__dict__.clear() self.Reset()
'Constructor for the RPC object. All arguments are optional, and simply set members on the class. These data members will be overriden by values passed to MakeCall.'
def __init__(self, *args, **kargs):
super(RPC, self).__init__(*args, **kargs) self.__result_dict = {}
'Waits on the API call associated with this RPC. The callback, if provided, will be executed before Wait() returns. If this RPC is already complete, or if the RPC was never started, this function will return immediately. Raises: InterruptedError if a callback throws an uncaught exception.'
def _WaitImpl(self):
try: rpc_completed = _apphosting_runtime___python__apiproxy.Wait(self) except (runtime.DeadlineExceededError, apiproxy_errors.InterruptedError): raise except: (exc_class, exc, tb) = sys.exc_info() if (isinstance(exc, SystemError) and (exc.args[0] == 'uncaught RPC except...
'Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field.'
def get_field_type(self, connection, table_name, row):
field_params = {} field_notes = [] try: field_type = connection.introspection.get_field_type(row[1], row) except KeyError: field_type = 'TextField' field_notes.append('This field type is a guess.') if (type(field_type) is tuple): (field_type, new_params...
'Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name.'
def get_meta(self, table_name):
return [' class Meta:', (' db_table = %r' % table_name), '']
'Return the Django version, which should be correct for all built-in Django commands. User-supplied commands should override this method.'
def get_version(self):
return django.get_version()
'Return a brief description of how to use this command, by default from the attribute ``self.help``.'
def usage(self, subcommand):
usage = ('%%prog %s [options] %s' % (subcommand, self.args)) if self.help: return ('%s\n\n%s' % (usage, self.help)) else: return usage
'Create and return the ``OptionParser`` which will be used to parse the arguments to this command.'
def create_parser(self, prog_name, subcommand):
return OptionParser(prog=prog_name, usage=self.usage(subcommand), version=self.get_version(), option_list=self.option_list)
'Print the help message for this command, derived from ``self.usage()``.'
def print_help(self, prog_name, subcommand):
parser = self.create_parser(prog_name, subcommand) parser.print_help()
'Set up any environment changes requested (e.g., Python path and Django settings), then run this command.'
def run_from_argv(self, argv):
parser = self.create_parser(argv[0], argv[1]) (options, args) = parser.parse_args(argv[2:]) handle_default_options(options) self.execute(*args, **options.__dict__)
'Try to execute this command, performing model validation if needed (as controlled by the attribute ``self.requires_model_validation``). If the command raises a ``CommandError``, intercept it and print it sensibly to stderr.'
def execute(self, *args, **options):
if self.can_import_settings: try: from google.appengine._internal.django.utils import translation translation.activate('en-us') except ImportError as e: sys.stderr.write(smart_str(self.style.ERROR(('Error: %s\n' % e)))) sys.exit(1) try: ...
'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 google.appengine._internal.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) ...
'The actual logic of the command. Subclasses must implement this method.'
def handle(self, *args, **options):
raise NotImplementedError()
'Perform the command\'s actions for ``app``, which will be the Python module corresponding to an application name given on the command line.'
def handle_app(self, app, **options):
raise NotImplementedError()
'Perform the command\'s actions for ``label``, which will be the string as given on the command line.'
def handle_label(self, label, **options):
raise NotImplementedError()
'Perform this command\'s actions.'
def handle_noargs(self, **options):
raise NotImplementedError()
'Output nothing. The lax options are included in the normal option parser, so under normal usage, we don\'t need to print the lax options.'
def print_help(self):
pass
'Output the basic options available to every command. This just redirects to the default print_help() behaviour.'
def print_lax_help(self):
OptionParser.print_help(self)
'Overrides OptionParser._process_args to exclusively handle default options and ignore args and other options. This overrides the behavior of the super class, which stop parsing at the first unrecognized option.'
def _process_args(self, largs, rargs, values):
while rargs: arg = rargs[0] try: if ((arg[0:2] == '--') and (len(arg) > 2)): self._process_long_opt(rargs, values) elif ((arg[:1] == '-') and (len(arg) > 1)): self._process_short_opts(rargs, values) else: del rargs[0...
'Returns the script\'s main help text, as a string.'
def main_help_text(self):
usage = ['', ("Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name), ''] usage.append('Available subcommands:') commands = get_commands().keys() commands.sort() for cmd in commands: usage.append((' %s' % cmd)) return '\n'....
'Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin.py" or "manage.py") if it can\'t be found.'
def fetch_command(self, subcommand):
try: app_name = get_commands()[subcommand] except KeyError: sys.stderr.write(("Unknown command: %r\nType '%s help' for usage.\n" % (subcommand, self.prog_name))) sys.exit(1) if isinstance(app_name, BaseCommand): klass = app_name else: klass = loa...
'Output completion suggestions for BASH. The output of this function is passed to BASH\'s `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used to get information about the cli input. Pl...
def autocomplete(self):
if (not os.environ.has_key('DJANGO_AUTO_COMPLETE')): return cwords = os.environ['COMP_WORDS'].split()[1:] cword = int(os.environ['COMP_CWORD']) try: curr = cwords[(cword - 1)] except IndexError: curr = '' subcommands = (get_commands().keys() + ['help']) options = [('-...
'Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it.'
def execute(self):
parser = LaxOptionParser(usage='%prog subcommand [options] [args]', version=get_version(), option_list=BaseCommand.option_list) self.autocomplete() try: (options, args) = parser.parse_args(self.argv) handle_default_options(options) except: pass try: subcomman...
'Return the total number of headers, including duplicates.'
def __len__(self):
return len(self._headers)
'Set the value of a header.'
def __setitem__(self, name, val):
del self[name] self._headers.append((name, val))
'Delete all occurrences of a header, if present. Does *not* raise an exception if the header is missing.'
def __delitem__(self, name):
name = name.lower() self._headers[:] = [kv for kv in self._headers if (kv[0].lower() != name)]
'Get the first header value for \'name\' Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, the first exactly which occurrance gets returned is undefined. Use getall() to get all the values matching a header field name.'
def __getitem__(self, name):
return self.get(name)
'Return true if the message contains the header.'
def has_key(self, name):
return (self.get(name) is not None)
'Return a list of all the values for the named field. These will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no fields exist with the given name, returns an emp...
def get_all(self, name):
name = name.lower() return [kv[1] for kv in self._headers if (kv[0].lower() == name)]
'Get the first header value for \'name\', or return \'default\''
def get(self, name, default=None):
name = name.lower() for (k, v) in self._headers: if (k.lower() == name): return v return default
'Return a list of all the header field names. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.'
def keys(self):
return [k for (k, v) in self._headers]
'Return a list of all header values. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.'
def values(self):
return [v for (k, v) in self._headers]
'Get all the header fields and values. These will be sorted in the order they were in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.'
def items(self):
return self._headers[:]
'str() returns the formatted headers, complete with end line, suitable for direct HTTP transmission.'
def __str__(self):
return '\r\n'.join(([('%s: %s' % kv) for kv in self._headers] + ['', '']))
'Return first matching header value for \'name\', or \'value\' If there is no header named \'name\', add a new header with name \'name\' and value \'value\'.'
def setdefault(self, name, value):
result = self.get(name) if (result is None): self._headers.append((name, value)) return value else: return result
'Extended header setting. _name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. Example: h.add_header(\...
def add_header(self, _name, _value, **_params):
parts = [] if (_value is not None): parts.append(_value) for (k, v) in _params.items(): if (v is None): parts.append(k.replace('_', '-')) else: parts.append(_formatparam(k.replace('_', '-'), v)) self._headers.append((_name, '; '.join(parts)))
'Invoke the application'
def run(self, application):
try: self.setup_environ() self.result = application(self.environ, self.start_response) self.finish_response() except: try: self.handle_error() except: self.close() raise
'Set up the environment for one request'
def setup_environ(self):
env = self.environ = self.os_environ.copy() self.add_cgi_vars() env['wsgi.input'] = self.get_stdin() env['wsgi.errors'] = self.get_stderr() env['wsgi.version'] = self.wsgi_version env['wsgi.run_once'] = self.wsgi_run_once env['wsgi.url_scheme'] = self.get_scheme() env['wsgi.multithread']...
'Send any iterable data, then close self and the iterable Subclasses intended for use in asynchronous servers will want to redefine this method, such that it sets up callbacks in the event loop to iterate over the data, and to call \'self.close()\' once the response is finished.'
def finish_response(self):
if ((not self.result_is_file()) or (not self.sendfile())): for data in self.result: self.write(data) self.finish_content() self.close()
'Return the URL scheme being used'
def get_scheme(self):
return guess_scheme(self.environ)
'Compute Content-Length or switch to chunked encoding if possible'
def set_content_length(self):
try: blocks = len(self.result) except (TypeError, AttributeError, NotImplementedError): pass else: if (blocks == 1): self.headers['Content-Length'] = str(self.bytes_sent) return
'Make any necessary header changes or defaults Subclasses can extend this to add other defaults.'
def cleanup_headers(self):
if ('Content-Length' not in self.headers): self.set_content_length()
'\'start_response()\' callable as specified by PEP 333'
def start_response(self, status, headers, exc_info=None):
if exc_info: try: if self.headers_sent: raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None elif (self.headers is not None): raise AssertionError('Headers already set!') assert isinstance(status, str), 'Status must ...
'Transmit version/status/date/server, via self._write()'
def send_preamble(self):
if self.origin_server: if self.client_is_modern(): self._write(('HTTP/%s %s\r\n' % (self.http_version, self.status))) if ('Date' not in self.headers): self._write(('Date: %s\r\n' % http_date())) if (self.server_software and ('Server' not in self.head...
'\'write()\' callable as specified by PEP 333'
def write(self, data):
assert isinstance(data, str), 'write() argument must be string' if (not self.status): raise AssertionError('write() before start_response()') elif (not self.headers_sent): self.bytes_sent = len(data) self.send_headers() else: self.bytes_sent += len(data)...
'Platform-specific file transmission Override this method in subclasses to support platform-specific file transmission. It is only called if the application\'s return iterable (\'self.result\') is an instance of \'self.wsgi_file_wrapper\'. This method should return a true value if it was able to actually transmit the ...
def sendfile(self):
return False
'Ensure headers and content have both been sent'
def finish_content(self):
if (not self.headers_sent): self.headers['Content-Length'] = '0' self.send_headers() else: pass