signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def format_if(value, format_kwargs):
if not value:<EOL><INDENT>return value<EOL><DEDENT>return value.format_map(format_kwargs)<EOL>
Apply format args to value if value or return value as is.
f3791:m2
def load_object(obj) -> object:
if isinstance(obj, str):<EOL><INDENT>if '<STR_LIT::>' in obj:<EOL><INDENT>module_name, obj_name = obj.split('<STR_LIT::>')<EOL>if not module_name:<EOL><INDENT>module_name = '<STR_LIT:.>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>module_name = obj<EOL><DEDENT>obj = importlib.import_module(module_name)<EOL>if obj_name:<EOL><INDENT>attrs = obj_name.split('<STR_LIT:.>')<EOL>for attr in attrs:<EOL><INDENT>obj = getattr(obj, attr)<EOL><DEDENT><DEDENT><DEDENT>return obj<EOL>
Load an object. Args: obj (str|object): Load the indicated object if this is a string; otherwise, return the object as is. To load a module, pass a dotted path like 'package.module'; to load an an object from a module pass a path like 'package.module:name'. Returns: object
f3791:m4
def merge_dicts(*dicts):
return functools.reduce(_merge_dicts, dicts, {})<EOL>
Merge all dicts. Dicts later in the list take precedence over dicts earlier in the list.
f3791:m5
def confirm(prompt='<STR_LIT>', color='<STR_LIT>', yes_values=('<STR_LIT:y>', '<STR_LIT:yes>'),<EOL>abort_on_unconfirmed=False, abort_options=None):
if isinstance(yes_values, str):<EOL><INDENT>yes_values = (yes_values,)<EOL><DEDENT>prompt = '<STR_LIT>'.format(prompt=prompt, yes_value=yes_values[<NUM_LIT:0>])<EOL>if color:<EOL><INDENT>prompt = printer.colorize(prompt, color=color)<EOL><DEDENT>try:<EOL><INDENT>answer = input(prompt)<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print()<EOL>confirmed = False<EOL><DEDENT>else:<EOL><INDENT>answer = answer.strip().lower()<EOL>confirmed = answer in yes_values<EOL><DEDENT>do_abort_on_unconfirmed = not confirmed and (<EOL>bool(abort_on_unconfirmed) or<EOL>(abort_on_unconfirmed == <NUM_LIT:0> and abort_on_unconfirmed is not False)<EOL>)<EOL>if do_abort_on_unconfirmed:<EOL><INDENT>if abort_options is None:<EOL><INDENT>abort_options = {}<EOL><DEDENT>if abort_on_unconfirmed is True:<EOL><INDENT>abort_options.setdefault('<STR_LIT>', <NUM_LIT:0>)<EOL><DEDENT>elif isinstance(abort_on_unconfirmed, int):<EOL><INDENT>abort_options.setdefault('<STR_LIT>', abort_on_unconfirmed)<EOL><DEDENT>elif isinstance(abort_on_unconfirmed, str):<EOL><INDENT>abort_options.setdefault('<STR_LIT:message>', abort_on_unconfirmed)<EOL><DEDENT>else:<EOL><INDENT>abort_options.setdefault('<STR_LIT>', <NUM_LIT:0>)<EOL><DEDENT>abort(**abort_options)<EOL><DEDENT>return confirmed<EOL>
Prompt for confirmation. Confirmation can be aborted by typing in a no value instead of one of the yes values or with Ctrl-C. Args: prompt (str): Prompt to present user ["Really?"] color (string|Color|bool) Color to print prompt string; can be ``False`` or ``None`` to print without color ["yellow"] yes_values (list[str]): Values user must type in to confirm [("y", "yes")] abort_on_unconfirmed (bool|int|str): When user does *not* confirm: - If this is an integer, print "Aborted" to stdout if it's 0 or to stderr if it's not 0 and then exit with this code - If this is a string, print it to stdout and exit with code 0 - If this is ``True`` (or any other truthy value), print "Aborted" to stdout and exit with code 0 abort_options (dict): Options to pass to :func:`abort` when not confirmed (these options will override any options set via ``abort_on_unconfirmed``)
f3792:m0
def camel_to_underscore(name):
name = re.sub(r'<STR_LIT>', r'<STR_LIT>', name)<EOL>name = re.sub(r'<STR_LIT>', r'<STR_LIT>', name)<EOL>name = name.lower()<EOL>return name<EOL>
Convert camel case name to underscore name. Examples:: >>> camel_to_underscore('HttpRequest') 'http_request' >>> camel_to_underscore('httpRequest') 'http_request' >>> camel_to_underscore('HTTPRequest') 'http_request' >>> camel_to_underscore('myHTTPRequest') 'my_http_request' >>> camel_to_underscore('MyHTTPRequest') 'my_http_request' >>> camel_to_underscore('my_http_request') 'my_http_request' >>> camel_to_underscore('MyHTTPRequestXYZ') 'my_http_request_xyz' >>> camel_to_underscore('_HTTPRequest') '_http_request' >>> camel_to_underscore('Request') 'request' >>> camel_to_underscore('REQUEST') 'request' >>> camel_to_underscore('_Request') '_request' >>> camel_to_underscore('__Request') '__request' >>> camel_to_underscore('_request') '_request' >>> camel_to_underscore('Request_') 'request_'
f3794:m0
def collect_commands(package_name=None, in_place=False, level=<NUM_LIT:1>):
commands = {}<EOL>frame = inspect.stack()[level][<NUM_LIT:0>]<EOL>f_globals = frame.f_globals<EOL>if package_name is None:<EOL><INDENT>package_name = f_globals['<STR_LIT>'].rsplit('<STR_LIT:.>', <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>package_paths = [os.path.dirname(f_globals['<STR_LIT>'])]<EOL><DEDENT>else:<EOL><INDENT>package = importlib.import_module(package_name)<EOL>package_name = package.__name__<EOL>package_paths = package.__path__<EOL><DEDENT>for package_path in package_paths:<EOL><INDENT>package_path = pathlib.Path(package_path)<EOL>for file in package_path.rglob('<STR_LIT>'):<EOL><INDENT>rel_path = str(file.relative_to(package_path))<EOL>rel_path = rel_path[:-<NUM_LIT:3>]<EOL>module_name = rel_path.replace(os.sep, '<STR_LIT:.>')<EOL>module_name = '<STR_LIT:.>'.join((package_name, module_name))<EOL>module = importlib.import_module(module_name)<EOL>module_commands = get_commands_in_namespace(module)<EOL>commands.update(module_commands)<EOL><DEDENT><DEDENT>commands = OrderedDict((name, commands[name]) for name in sorted(commands))<EOL>if in_place:<EOL><INDENT>f_globals.update(commands)<EOL><DEDENT>return commands<EOL>
Collect commands from package and its subpackages. This replaces the tedium of adding and maintaining a bunch of imports like ``from .xyz import x, y, z`` in modules that are used to collect all of the commands in a package. Args: package_name (str): Package to collect from. If not passed, the package containing the module of the call site will be used. in_place (bool): If set, the call site's globals will be updated in place (using some frame magic). level (int): If not called from the global scope, set this appropriately to account for the call stack. Returns: OrderedDict: The commands found in the package, ordered by name. Example usage:: # mypackage.commands __all__ = list(collect_commands(in_place=True)) Less magical usage:: # mypackage.commands commands = collect_commands() globals().update(commands) __all__ = list(commands) .. note:: If ``package_name`` is passed and refers to a namespace package, all corresponding namespace package directories will be searched for commands.
f3795:m0
def get_commands_in_namespace(namespace=None, level=<NUM_LIT:1>):
from ..command import Command <EOL>commands = {}<EOL>if namespace is None:<EOL><INDENT>frame = inspect.stack()[level][<NUM_LIT:0>]<EOL>namespace = frame.f_globals<EOL><DEDENT>elif inspect.ismodule(namespace):<EOL><INDENT>namespace = vars(namespace)<EOL><DEDENT>for name in namespace:<EOL><INDENT>obj = namespace[name]<EOL>if isinstance(obj, Command):<EOL><INDENT>commands[name] = obj<EOL><DEDENT><DEDENT>return OrderedDict((name, commands[name]) for name in sorted(commands))<EOL>
Get commands in namespace. Args: namespace (dict|module): Typically a module. If not passed, the globals from the call site will be used. level (int): If not called from the global scope, set this appropriately to account for the call stack. Returns: OrderedDict: The commands found in the namespace, ordered by name. Can be used to create ``__all__`` lists:: __all__ = list(get_commands_in_namespace())
f3795:m1
def implementation(self,<EOL>commands_module: arg(short_option='<STR_LIT>') = DEFAULT_COMMANDS_MODULE,<EOL>config_file: arg(short_option='<STR_LIT>') = None,<EOL>globals_: arg(<EOL>container=dict,<EOL>type=json_value,<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>) = None,<EOL>env: arg(help='<STR_LIT>') = None,<EOL>version: arg(help='<STR_LIT>') = None,<EOL>echo: arg(<EOL>type=bool,<EOL>help='<STR_LIT>',<EOL>inverse_help='<STR_LIT>'<EOL>) = None,<EOL>environ: arg(<EOL>container=dict,<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>) = None,<EOL>info: arg(help='<STR_LIT>') = False,<EOL>list_commands: arg(help='<STR_LIT>') = False,<EOL>debug: arg(<EOL>type=bool,<EOL>help='<STR_LIT>'<EOL>) = None,<EOL>*,<EOL>all_argv=(),<EOL>run_argv=(),<EOL>command_argv=(),<EOL>cli_args=()):
collection = Collection.load_from_module(commands_module)<EOL>config_file = self.find_config_file(config_file)<EOL>cli_globals = globals_ or {}<EOL>if env:<EOL><INDENT>cli_globals['<STR_LIT>'] = env<EOL><DEDENT>if version:<EOL><INDENT>cli_globals['<STR_LIT:version>'] = version<EOL><DEDENT>if echo is not None:<EOL><INDENT>cli_globals['<STR_LIT>'] = echo<EOL><DEDENT>if debug is not None:<EOL><INDENT>cli_globals['<STR_LIT>'] = debug<EOL><DEDENT>if config_file:<EOL><INDENT>args_from_file = self.read_config_file(config_file, collection)<EOL>args = merge_dicts(args_from_file, {'<STR_LIT>': environ or {}})<EOL>config_file_globals = args['<STR_LIT>']<EOL>env = cli_globals.get('<STR_LIT>') or config_file_globals.get('<STR_LIT>')<EOL>if env:<EOL><INDENT>envs = args['<STR_LIT>']<EOL>try:<EOL><INDENT>env_globals = envs[env]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise RunnerError('<STR_LIT>'.format_map(locals()))<EOL><DEDENT>globals_ = merge_dicts(config_file_globals, env_globals, cli_globals)<EOL>globals_['<STR_LIT>'] = envs<EOL><DEDENT>else:<EOL><INDENT>globals_ = merge_dicts(config_file_globals, cli_globals)<EOL><DEDENT>default_args = {name: {} for name in collection}<EOL>default_args = merge_dicts(default_args, args.get('<STR_LIT:args>') or {})<EOL>for command_name, command_default_args in default_args.items():<EOL><INDENT>command = collection[command_name]<EOL>for name in tuple(command_default_args):<EOL><INDENT>param = command.find_parameter(name)<EOL>if param is None:<EOL><INDENT>raise RunnerError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>.format_map(locals()))<EOL><DEDENT>if param is not None and name != param.name:<EOL><INDENT>command_default_args[param.name] = command_default_args.pop(name)<EOL><DEDENT><DEDENT>for name, value in globals_.items():<EOL><INDENT>param = command.find_parameter(name)<EOL>if param is not None:<EOL><INDENT>if param.name not in command_default_args:<EOL><INDENT>command_default_args[param.name] = value<EOL><DEDENT><DEDENT>elif command.has_kwargs:<EOL><INDENT>name = name.replace('<STR_LIT:->', '<STR_LIT:_>')<EOL>command_default_args[name] = value<EOL><DEDENT><DEDENT>for name, value in command_default_args.items():<EOL><INDENT>command_arg = command.find_arg(name)<EOL>if command_arg.container and isinstance(value, list):<EOL><INDENT>command_default_args[name] = command_arg.container(value)<EOL><DEDENT><DEDENT><DEDENT>default_args = {name: args for name, args in default_args.items() if args}<EOL>environ = args['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>globals_ = cli_globals<EOL>default_args = {}<EOL>environ = environ or {}<EOL><DEDENT>debug = globals_.get('<STR_LIT>', False)<EOL>show_info = info or list_commands or not command_argv or debug<EOL>print_and_exit = info or list_commands<EOL>globals_, default_args, environ = self.interpolate(globals_, default_args, environ)<EOL>if show_info:<EOL><INDENT>print('<STR_LIT>', __version__)<EOL><DEDENT>if debug:<EOL><INDENT>print()<EOL>printer.debug('<STR_LIT>', commands_module)<EOL>printer.debug('<STR_LIT>', config_file)<EOL>printer.debug('<STR_LIT>', all_argv)<EOL>printer.debug('<STR_LIT>', run_argv)<EOL>printer.debug('<STR_LIT>', command_argv)<EOL>items = (<EOL>('<STR_LIT>', globals_),<EOL>('<STR_LIT>', default_args),<EOL>('<STR_LIT>', environ),<EOL>)<EOL>for label, data in items:<EOL><INDENT>if data:<EOL><INDENT>printer.debug(label)<EOL>for k in sorted(data):<EOL><INDENT>v = data[k]<EOL>printer.debug('<STR_LIT>'.format_map(locals()))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if environ:<EOL><INDENT>os.environ.update(environ)<EOL><DEDENT>collection.set_attrs(debug=debug)<EOL>collection.set_default_args(default_args)<EOL>runner = CommandRunner(collection, debug)<EOL>if print_and_exit:<EOL><INDENT>if list_commands:<EOL><INDENT>runner.print_usage()<EOL><DEDENT><DEDENT>elif not command_argv:<EOL><INDENT>printer.warning('<STR_LIT>')<EOL>runner.print_usage()<EOL><DEDENT>else:<EOL><INDENT>runner.run(command_argv)<EOL><DEDENT>
Run one or more commands in succession. For example, assume the commands ``local`` and ``remote`` have been defined; the following will run ``ls`` first on the local host and then on the remote host:: runcommands local ls remote <host> ls When a command name is encountered in ``argv``, it will be considered the starting point of the next command *unless* the previous item in ``argv`` was an option like ``--xyz`` that expects a value (i.e., it's not a flag). To avoid ambiguity when an option value matches a command name, the value can be prepended with a colon to force it to be considered a value and not a command name.
f3799:c0:m0
@command<EOL>def complete(command_line,<EOL>current_token,<EOL>position,<EOL>shell: arg(choices=('<STR_LIT>', '<STR_LIT>'))):
position = int(position)<EOL>tokens = shlex.split(command_line[:position])<EOL>all_argv, run_argv, command_argv = run.partition_argv(tokens[<NUM_LIT:1>:])<EOL>run_args = run.parse_args(run_argv)<EOL>module = run_args.get('<STR_LIT>')<EOL>module = module or DEFAULT_COMMANDS_MODULE<EOL>module = normalize_path(module)<EOL>try:<EOL><INDENT>collection = Collection.load_from_module(module)<EOL><DEDENT>except Exception:<EOL><INDENT>collection = {}<EOL><DEDENT>found_command = find_command(collection, tokens) or run<EOL>if current_token:<EOL><INDENT>if current_token.startswith('<STR_LIT:->'):<EOL><INDENT>if current_token not in found_command.option_map:<EOL><INDENT>print_command_options(found_command, current_token)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print_commands(collection, shell)<EOL>path = os.path.expanduser(current_token)<EOL>path = os.path.expandvars(path)<EOL>paths = glob.glob('<STR_LIT>' % path)<EOL>if paths:<EOL><INDENT>for entry in paths:<EOL><INDENT>if os.path.isdir(entry):<EOL><INDENT>print('<STR_LIT>' % entry)<EOL><DEDENT>else:<EOL><INDENT>print(entry)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>option = found_command.option_map.get(tokens[-<NUM_LIT:1>])<EOL>if option and option.takes_value:<EOL><INDENT>if option.choices:<EOL><INDENT>for choice in option.choices:<EOL><INDENT>print(choice)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for entry in os.listdir():<EOL><INDENT>if os.path.isdir(entry):<EOL><INDENT>print('<STR_LIT>' % entry)<EOL><DEDENT>else:<EOL><INDENT>print(entry)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>print_command_options(found_command)<EOL>print_commands(collection, shell)<EOL><DEDENT><DEDENT>
Find completions for current command. This assumes that we'll handle all completion logic here and that the shell's automatic file name completion is disabled. Args: command_line: Command line current_token: Token at cursor position: Current cursor position shell: Name of shell
f3800:m0
def json_value(string):
try:<EOL><INDENT>string = json.loads(string)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>return string<EOL>
Convert string to JSON if possible; otherwise, return as is.
f3802:m0
def init(script=sys.argv[<NUM_LIT:0>], base='<STR_LIT>', append=True, ignore=['<STR_LIT:/>','<STR_LIT>'], realpath=False, pythonpath=False, throw=False):
if type(ignore) is str: ignore = [ignore]<EOL>script = os.path.realpath(script) if realpath else os.path.abspath(script)<EOL>path = os.path.dirname(script)<EOL>while os.path.dirname(path) != path and (path in ignore or not os.path.isdir(os.path.join(path, base))):<EOL><INDENT>path = os.path.dirname(path)<EOL><DEDENT>modules_dir = os.path.join(path, base)<EOL>if path not in ignore and os.path.isdir(modules_dir):<EOL><INDENT>if append: sys.path.append(modules_dir)<EOL>else: sys.path.insert(<NUM_LIT:1>, modules_dir)<EOL>if pythonpath:<EOL><INDENT>if '<STR_LIT>' not in os.environ: os.environ['<STR_LIT>'] = '<STR_LIT>'<EOL>if not append: os.environ['<STR_LIT>'] += modules_dir<EOL>if os.environ['<STR_LIT>'] != '<STR_LIT>': os.environ['<STR_LIT>'] += os.pathsep<EOL>if append: os.environ['<STR_LIT>'] += modules_dir<EOL><DEDENT>return modules_dir<EOL><DEDENT>elif throw:<EOL><INDENT>raise Exception("<STR_LIT>" % (base, script))<EOL><DEDENT>return None<EOL>
Parameters: * `script`: Path to script file. Default is currently running script file * `base`: Name of base module directory to add to sys.path. Default is "lib". * `append`: Append module directory to the end of sys.path, or insert at the beginning? Default is to append. * `ignore`: List of directories to ignore during the module search. Default is to ignore "/" and "/usr". * `realpath`: Should symlinks be resolved first? Default is False. * `pythonpath`: Should the modules directory be added to the PYTHONPATH environment variable? Default is False. * `throw`: Should an exception be thrown if no modules directory was found? Default is False. Returns: * The path to the modules directory if it was found, otherwise None.
f3807:m0
@classmethod<EOL><INDENT>def _remap_fields(cls, kwargs):<DEDENT>
mapped = {}<EOL>for key in kwargs:<EOL><INDENT>if key in cls._remap:<EOL><INDENT>mapped[cls._remap[key]] = kwargs[key]<EOL><DEDENT>else:<EOL><INDENT>mapped[key] = kwargs[key]<EOL><DEDENT><DEDENT>return mapped<EOL>
Map fields from kwargs into dict acceptable by NIOS
f3815:c0:m5
def __init__(self, ea_dict=None):
if ea_dict is None:<EOL><INDENT>ea_dict = {}<EOL><DEDENT>self._ea_dict = ea_dict<EOL>
Optionally accept EAs as a dict on init. Expected EA format is {ea_name: ea_value}
f3815:c1:m0
@property<EOL><INDENT>def ea_dict(self):<DEDENT>
return self._ea_dict.copy()<EOL>
Returns dict with EAs in {ea_name: ea_value} format.
f3815:c1:m2
@classmethod<EOL><INDENT>def from_dict(cls, eas_from_nios):<DEDENT>
if not eas_from_nios:<EOL><INDENT>return<EOL><DEDENT>return cls({name: cls._process_value(ib_utils.try_value_to_bool,<EOL>eas_from_nios[name]['<STR_LIT:value>'])<EOL>for name in eas_from_nios})<EOL>
Converts extensible attributes from the NIOS reply.
f3815:c1:m3
def to_dict(self):
return {name: {'<STR_LIT:value>': self._process_value(str, value)}<EOL>for name, value in self._ea_dict.items()<EOL>if not (value is None or value == "<STR_LIT>" or value == [])}<EOL>
Converts extensible attributes into the format suitable for NIOS.
f3815:c1:m4
@staticmethod<EOL><INDENT>def _process_value(func, value):<DEDENT>
if isinstance(value, (list, tuple)):<EOL><INDENT>return [func(item) for item in value]<EOL><DEDENT>return func(value)<EOL>
Applies processing method for value or each element in it. :param func: method to be called with value :param value: value to process :return: if 'value' is list/tupe, returns iterable with func results, else func result is returned
f3815:c1:m5
def get(self, name, default=None):
return self._ea_dict.get(name, default)<EOL>
Return value of requested EA.
f3815:c1:m6
def set(self, name, value):
self._ea_dict[name] = value<EOL>
Set value of requested EA.
f3815:c1:m7
@classmethod<EOL><INDENT>def from_dict(cls, connector, ip_dict):<DEDENT>
mapping = cls._global_field_processing.copy()<EOL>mapping.update(cls._custom_field_processing)<EOL>for field in mapping:<EOL><INDENT>if field in ip_dict:<EOL><INDENT>ip_dict[field] = mapping[field](ip_dict[field])<EOL><DEDENT><DEDENT>return cls(connector, **ip_dict)<EOL>
Build dict fields as SubObjects if needed. Checks if lambda for building object from dict exists. _global_field_processing and _custom_field_processing rules are checked.
f3815:c2:m3
def field_to_dict(self, field):
value = getattr(self, field)<EOL>if isinstance(value, (list, tuple)):<EOL><INDENT>return [self.value_to_dict(val) for val in value]<EOL><DEDENT>return self.value_to_dict(value)<EOL>
Read field value and converts to dict if possible
f3815:c2:m5
def to_dict(self, search_fields=None):
fields = self._fields<EOL>if search_fields == '<STR_LIT>':<EOL><INDENT>fields = self._search_for_update_fields<EOL><DEDENT>elif search_fields == '<STR_LIT:all>':<EOL><INDENT>fields = self._all_searchable_fields<EOL><DEDENT>elif search_fields == '<STR_LIT>':<EOL><INDENT>fields = [field for field in self._fields<EOL>if field in self._updateable_search_fields or<EOL>field not in self._search_for_update_fields]<EOL><DEDENT>return {field: self.field_to_dict(field) for field in fields<EOL>if getattr(self, field, None) is not None}<EOL>
Builds dict without None object fields
f3815:c2:m6
def fetch(self, only_ref=False):
if self.ref:<EOL><INDENT>reply = self.connector.get_object(<EOL>self.ref, return_fields=self.return_fields)<EOL>if reply:<EOL><INDENT>self.update_from_dict(reply)<EOL>return True<EOL><DEDENT><DEDENT>search_dict = self.to_dict(search_fields='<STR_LIT>')<EOL>return_fields = [] if only_ref else self.return_fields<EOL>reply = self.connector.get_object(self.infoblox_type,<EOL>search_dict,<EOL>return_fields=return_fields)<EOL>if reply:<EOL><INDENT>self.update_from_dict(reply[<NUM_LIT:0>], only_ref=only_ref)<EOL>return True<EOL><DEDENT>return False<EOL>
Fetch object from NIOS by _ref or searchfields Update existent object with fields returned from NIOS Return True on successful object fetch
f3815:c2:m13
def _ip_setter(self, ipaddr_name, ipaddrs_name, ips):
if isinstance(ips, six.string_types):<EOL><INDENT>setattr(self, ipaddr_name, ips)<EOL><DEDENT>elif isinstance(ips, (list, tuple)) and isinstance(ips[<NUM_LIT:0>], IP):<EOL><INDENT>setattr(self, ipaddr_name, ips[<NUM_LIT:0>].ip)<EOL>setattr(self, ipaddrs_name, ips)<EOL><DEDENT>elif isinstance(ips, IP):<EOL><INDENT>setattr(self, ipaddr_name, ips.ip)<EOL>setattr(self, ipaddrs_name, [ips])<EOL><DEDENT>elif ips is None:<EOL><INDENT>setattr(self, ipaddr_name, None)<EOL>setattr(self, ipaddrs_name, None)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % ips)<EOL><DEDENT>
Setter for ip fields Accept as input string or list of IP instances. String case: only ipvXaddr is going to be filled, that is enough to perform host record search using ip List of IP instances case: ipvXaddrs is going to be filled with ips content, so create can be issues, since fully prepared IP objects in place. ipXaddr is also filled to be able perform search on NIOS and verify that no such host record exists yet.
f3815:c6:m2
@ipv4addrs.setter<EOL><INDENT>def ipv4addrs(self, ips):<DEDENT>
self._ip_setter('<STR_LIT>', '<STR_LIT>', ips)<EOL>
Setter for ipv4addrs/ipv4addr
f3815:c7:m1
@ipv6addrs.setter<EOL><INDENT>def ipv6addrs(self, ips):<DEDENT>
self._ip_setter('<STR_LIT>', '<STR_LIT>', ips)<EOL>
Setter for ipv6addrs/ipv6addr
f3815:c8:m1
@mac.setter<EOL><INDENT>def mac(self, mac):<DEDENT>
self._mac = mac<EOL>if mac:<EOL><INDENT>self.duid = ib_utils.generate_duid(mac)<EOL><DEDENT>elif not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.duid = None<EOL><DEDENT>
Set mac and duid fields To have common interface with FixedAddress accept mac address and set duid as a side effect. 'mac' was added to _shadow_fields to prevent sending it out over wapi.
f3815:c21:m1
def create_network(self, net_view_name, cidr, nameservers=None,<EOL>members=None, gateway_ip=None, dhcp_trel_ip=None,<EOL>network_extattrs=None):
ipv4 = ib_utils.determine_ip_version(cidr) == <NUM_LIT:4><EOL>options = []<EOL>if nameservers:<EOL><INDENT>options.append(obj.DhcpOption(name='<STR_LIT>',<EOL>value="<STR_LIT:U+002C>".join(nameservers)))<EOL><DEDENT>if ipv4 and gateway_ip:<EOL><INDENT>options.append(obj.DhcpOption(name='<STR_LIT>',<EOL>value=gateway_ip))<EOL><DEDENT>if ipv4 and dhcp_trel_ip:<EOL><INDENT>options.append(obj.DhcpOption(name='<STR_LIT>',<EOL>num=<NUM_LIT>,<EOL>value=dhcp_trel_ip))<EOL><DEDENT>return obj.Network.create(self.connector,<EOL>network_view=net_view_name,<EOL>cidr=cidr,<EOL>members=members,<EOL>options=options,<EOL>extattrs=network_extattrs,<EOL>check_if_exists=False)<EOL>
Create NIOS Network and prepare DHCP options. Some DHCP options are valid for IPv4 only, so just skip processing them for IPv6 case. :param net_view_name: network view name :param cidr: network to allocate, example '172.23.23.0/24' :param nameservers: list of name servers hosts/ip :param members: list of objects.AnyMember objects that are expected to serve dhcp for created network :param gateway_ip: gateway ip for the network (valid for IPv4 only) :param dhcp_trel_ip: ip address of dhcp relay (valid for IPv4 only) :param network_extattrs: extensible attributes for network (instance of objects.EA) :returns: created network (instance of objects.Network)
f3817:c0:m5
def create_ip_range(self, network_view, start_ip, end_ip, network,<EOL>disable, range_extattrs):
return obj.IPRange.create(self.connector,<EOL>network_view=network_view,<EOL>start_addr=start_ip,<EOL>end_addr=end_ip,<EOL>cidr=network,<EOL>disable=disable,<EOL>extattrs=range_extattrs,<EOL>check_if_exists=False)<EOL>
Creates IPRange or fails if already exists.
f3817:c0:m7
def network_exists(self, network_view, cidr):
LOG.warning(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>network = obj.Network.search(self.connector,<EOL>network_view=network_view,<EOL>cidr=cidr)<EOL>return network is not None<EOL>
Deprecated, use get_network() instead.
f3817:c0:m10
def delete_objects_associated_with_a_record(self, name, view, delete_list):
search_objects = {}<EOL>if '<STR_LIT>' in delete_list:<EOL><INDENT>search_objects['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' in delete_list:<EOL><INDENT>search_objects['<STR_LIT>'] = '<STR_LIT:name>'<EOL><DEDENT>if not search_objects:<EOL><INDENT>return<EOL><DEDENT>for obj_type, search_type in search_objects.items():<EOL><INDENT>payload = {'<STR_LIT>': view,<EOL>search_type: name}<EOL>ib_objs = self.connector.get_object(obj_type, payload)<EOL>if ib_objs:<EOL><INDENT>for ib_obj in ib_objs:<EOL><INDENT>self.delete_object_by_ref(ib_obj['<STR_LIT>'])<EOL><DEDENT><DEDENT><DEDENT>
Deletes records associated with record:a or record:aaaa.
f3817:c0:m43
def generate_duid(mac):
valid = mac and isinstance(mac, six.string_types)<EOL>if not valid:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return "<STR_LIT>" + mac[<NUM_LIT:9>:] + "<STR_LIT::>" + mac<EOL>
DUID is consisted of 10 hex numbers. 0x00 + mac with last 3 hex + mac with 6 hex
f3818:m1
def try_value_to_bool(value, strict_mode=True):
if strict_mode:<EOL><INDENT>true_list = ('<STR_LIT:True>',)<EOL>false_list = ('<STR_LIT:False>',)<EOL>val = value<EOL><DEDENT>else:<EOL><INDENT>true_list = ('<STR_LIT:true>', '<STR_LIT>', '<STR_LIT:yes>')<EOL>false_list = ('<STR_LIT:false>', '<STR_LIT>', '<STR_LIT>')<EOL>val = str(value).lower()<EOL><DEDENT>if val in true_list:<EOL><INDENT>return True<EOL><DEDENT>elif val in false_list:<EOL><INDENT>return False<EOL><DEDENT>return value<EOL>
Tries to convert value into boolean. strict_mode is True: - Only string representation of str(True) and str(False) are converted into booleans; - Otherwise unchanged incoming value is returned; strict_mode is False: - Anything that looks like True or False is converted into booleans. Values accepted as True: - 'true', 'on', 'yes' (case independent) Values accepted as False: - 'false', 'off', 'no' (case independent) - all other values are returned unchanged
f3818:m4
def _parse_options(self, options):
attributes = ('<STR_LIT:host>', '<STR_LIT>', '<STR_LIT:username>', '<STR_LIT:password>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>')<EOL>for attr in attributes:<EOL><INDENT>if isinstance(options, dict) and attr in options:<EOL><INDENT>setattr(self, attr, options[attr])<EOL><DEDENT>elif hasattr(options, attr):<EOL><INDENT>value = getattr(options, attr)<EOL>setattr(self, attr, value)<EOL><DEDENT>elif attr in self.DEFAULT_OPTIONS:<EOL><INDENT>setattr(self, attr, self.DEFAULT_OPTIONS[attr])<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>" % attr<EOL>raise ib_ex.InfobloxConfigException(msg=msg)<EOL><DEDENT><DEDENT>for attr in ('<STR_LIT:host>', '<STR_LIT:username>', '<STR_LIT:password>'):<EOL><INDENT>if not getattr(self, attr):<EOL><INDENT>msg = "<STR_LIT>" % attr<EOL>raise ib_ex.InfobloxConfigException(msg=msg)<EOL><DEDENT><DEDENT>self.wapi_url = "<STR_LIT>" % (self.host,<EOL>self.wapi_version)<EOL>self.cloud_api_enabled = self.is_cloud_wapi(self.wapi_version)<EOL>
Copy needed options to self
f3819:c0:m1
@staticmethod<EOL><INDENT>def _parse_reply(request):<DEDENT>
try:<EOL><INDENT>return jsonutils.loads(request.content)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ib_ex.InfobloxConnectionError(reason=request.content)<EOL><DEDENT>
Tries to parse reply from NIOS. Raises exception with content if reply is not in json format
f3819:c0:m8
@reraise_neutron_exception<EOL><INDENT>def get_object(self, obj_type, payload=None, return_fields=None,<EOL>extattrs=None, force_proxy=False, max_results=None,<EOL>paging=False):<DEDENT>
self._validate_obj_type_or_die(obj_type, obj_type_expected=False)<EOL>if max_results is None and self.max_results:<EOL><INDENT>max_results = self.max_results<EOL><DEDENT>if paging is False and self.paging:<EOL><INDENT>paging = self.paging<EOL><DEDENT>query_params = self._build_query_params(payload=payload,<EOL>return_fields=return_fields,<EOL>max_results=max_results,<EOL>paging=paging)<EOL>proxy_flag = self.cloud_api_enabled and force_proxy<EOL>ib_object = self._handle_get_object(obj_type, query_params, extattrs,<EOL>proxy_flag)<EOL>if ib_object:<EOL><INDENT>return ib_object<EOL><DEDENT>if self.cloud_api_enabled and not force_proxy:<EOL><INDENT>ib_object = self._handle_get_object(obj_type, query_params,<EOL>extattrs, proxy_flag=True)<EOL>if ib_object:<EOL><INDENT>return ib_object<EOL><DEDENT><DEDENT>return None<EOL>
Retrieve a list of Infoblox objects of type 'obj_type' Some get requests like 'ipv4address' should be always proxied to GM on Hellfire If request is cloud and proxy is not forced yet, then plan to do 2 request: - the first one is not proxied to GM - the second is proxied to GM Args: obj_type (str): Infoblox object type, e.g. 'network', 'range', etc. payload (dict): Payload with data to send return_fields (list): List of fields to be returned extattrs (dict): List of Extensible Attributes force_proxy (bool): Set _proxy_search flag to process requests on GM max_results (int): Maximum number of objects to be returned. If set to a negative number the appliance will return an error when the number of returned objects would exceed the setting. The default is -1000. If this is set to a positive number, the results will be truncated when necessary. paging (bool): Enables paging to wapi calls if paging = True, it uses _max_results to set paging size of the wapi calls. If _max_results is negative it will take paging size as 1000. Returns: A list of the Infoblox objects requested Raises: InfobloxObjectNotFound
f3819:c0:m10
@reraise_neutron_exception<EOL><INDENT>def create_object(self, obj_type, payload, return_fields=None):<DEDENT>
self._validate_obj_type_or_die(obj_type)<EOL>query_params = self._build_query_params(return_fields=return_fields)<EOL>url = self._construct_url(obj_type, query_params)<EOL>opts = self._get_request_options(data=payload)<EOL>self._log_request('<STR_LIT>', url, opts)<EOL>if(self.session.cookies):<EOL><INDENT>self.session.auth = None<EOL><DEDENT>r = self.session.post(url, **opts)<EOL>self._validate_authorized(r)<EOL>if r.status_code != requests.codes.CREATED:<EOL><INDENT>response = utils.safe_json_load(r.content)<EOL>already_assigned = '<STR_LIT>'<EOL>if response and already_assigned in response.get('<STR_LIT:text>'):<EOL><INDENT>exception = ib_ex.InfobloxMemberAlreadyAssigned<EOL><DEDENT>else:<EOL><INDENT>exception = ib_ex.InfobloxCannotCreateObject<EOL><DEDENT>raise exception(<EOL>response=response,<EOL>obj_type=obj_type,<EOL>content=r.content,<EOL>args=payload,<EOL>code=r.status_code)<EOL><DEDENT>return self._parse_reply(r)<EOL>
Create an Infoblox object of type 'obj_type' Args: obj_type (str): Infoblox object type, e.g. 'network', 'range', etc. payload (dict): Payload with data to send return_fields (list): List of fields to be returned Returns: The object reference of the newly create object Raises: InfobloxException
f3819:c0:m13
@reraise_neutron_exception<EOL><INDENT>def update_object(self, ref, payload, return_fields=None):<DEDENT>
query_params = self._build_query_params(return_fields=return_fields)<EOL>opts = self._get_request_options(data=payload)<EOL>url = self._construct_url(ref, query_params)<EOL>self._log_request('<STR_LIT>', url, opts)<EOL>r = self.session.put(url, **opts)<EOL>self._validate_authorized(r)<EOL>if r.status_code != requests.codes.ok:<EOL><INDENT>self._check_service_availability('<STR_LIT>', r, ref)<EOL>raise ib_ex.InfobloxCannotUpdateObject(<EOL>response=jsonutils.loads(r.content),<EOL>ref=ref,<EOL>content=r.content,<EOL>code=r.status_code)<EOL><DEDENT>return self._parse_reply(r)<EOL>
Update an Infoblox object Args: ref (str): Infoblox object reference payload (dict): Payload with data to send Returns: The object reference of the updated object Raises: InfobloxException
f3819:c0:m16
@reraise_neutron_exception<EOL><INDENT>def delete_object(self, ref, delete_arguments=None):<DEDENT>
opts = self._get_request_options()<EOL>if not isinstance(delete_arguments, dict):<EOL><INDENT>delete_arguments = {}<EOL><DEDENT>url = self._construct_url(ref, query_params=delete_arguments)<EOL>self._log_request('<STR_LIT>', url, opts)<EOL>r = self.session.delete(url, **opts)<EOL>self._validate_authorized(r)<EOL>if r.status_code != requests.codes.ok:<EOL><INDENT>self._check_service_availability('<STR_LIT>', r, ref)<EOL>raise ib_ex.InfobloxCannotDeleteObject(<EOL>response=jsonutils.loads(r.content),<EOL>ref=ref,<EOL>content=r.content,<EOL>code=r.status_code)<EOL><DEDENT>return self._parse_reply(r)<EOL>
Remove an Infoblox object Args: ref (str): Object reference delete_arguments (dict): Extra delete arguments Returns: The object reference of the removed object Raises: InfobloxException
f3819:c0:m17
def parse_headers(content_disposition, location=None, relaxed=False):
LOGGER.debug(<EOL>'<STR_LIT>', content_disposition, location)<EOL>if content_disposition is None:<EOL><INDENT>return ContentDisposition(location=location)<EOL><DEDENT>if False:<EOL><INDENT>content_disposition = ensure_charset(content_disposition, '<STR_LIT:ascii>')<EOL><DEDENT>else:<EOL><INDENT>content_disposition = ensure_charset(content_disposition, '<STR_LIT>')<EOL><DEDENT>if relaxed:<EOL><INDENT>content_disposition = normalize_ws(content_disposition)<EOL>parser = content_disposition_value_relaxed<EOL><DEDENT>else:<EOL><INDENT>if not is_lws_safe(content_disposition):<EOL><INDENT>raise ValueError(<EOL>content_disposition, '<STR_LIT>')<EOL><DEDENT>parser = content_disposition_value<EOL><DEDENT>try:<EOL><INDENT>parsed = parser.parse(content_disposition)<EOL><DEDENT>except FullFirstMatchException:<EOL><INDENT>return ContentDisposition(location=location)<EOL><DEDENT>return ContentDisposition(<EOL>disposition=parsed[<NUM_LIT:0>], assocs=parsed[<NUM_LIT:1>:], location=location)<EOL>
Build a ContentDisposition from header values.
f3824:m1
def parse_httplib2_response(response, **kwargs):
return parse_headers(<EOL>response.get('<STR_LIT>'),<EOL>response['<STR_LIT>'], **kwargs)<EOL>
Build a ContentDisposition from an httplib2 response.
f3824:m2
def parse_requests_response(response, **kwargs):
return parse_headers(<EOL>response.headers.get('<STR_LIT>'), response.url, **kwargs)<EOL>
Build a ContentDisposition from a requests (PyPI) response.
f3824:m3
def build_header(<EOL>filename, disposition='<STR_LIT>', filename_compat=None<EOL>):
<EOL>if disposition != '<STR_LIT>':<EOL><INDENT>assert is_token(disposition)<EOL><DEDENT>rv = disposition<EOL>if is_token(filename):<EOL><INDENT>rv += '<STR_LIT>' % (filename, )<EOL>return rv<EOL><DEDENT>elif is_ascii(filename) and is_lws_safe(filename):<EOL><INDENT>qd_filename = qd_quote(filename)<EOL>rv += '<STR_LIT>' % (qd_filename, )<EOL>if qd_filename == filename:<EOL><INDENT>return rv<EOL><DEDENT><DEDENT>elif filename_compat:<EOL><INDENT>if is_token(filename_compat):<EOL><INDENT>rv += '<STR_LIT>' % (filename_compat, )<EOL><DEDENT>else:<EOL><INDENT>assert is_lws_safe(filename_compat)<EOL>rv += '<STR_LIT>' % (qd_quote(filename_compat), )<EOL><DEDENT><DEDENT>rv += "<STR_LIT>" % (percent_encode(<EOL>filename, safe=attr_chars_nonalnum, encoding='<STR_LIT:utf-8>'), )<EOL>return rv.encode('<STR_LIT>')<EOL>
Generate a Content-Disposition header for a given filename. For legacy clients that don't understand the filename* parameter, a filename_compat value may be given. It should either be ascii-only (recommended) or iso-8859-1 only. In the later case it should be a character string (unicode in Python 2). Options for generating filename_compat (only useful for legacy clients): - ignore (will only send filename*); - strip accents using unicode's decomposing normalisations, which can be done from unicode data (stdlib), and keep only ascii; - use the ascii transliteration tables from Unidecode (PyPI); - use iso-8859-1 Ignore is the safest, and can be used to trigger a fallback to the document location (which can be percent-encoded utf-8 if you control the URLs). See https://tools.ietf.org/html/rfc6266#appendix-D
f3824:m14
def __init__(self, disposition='<STR_LIT>', assocs=None, location=None):
self.disposition = disposition<EOL>self.location = location<EOL>if assocs is None:<EOL><INDENT>self.assocs = {}<EOL><DEDENT>else:<EOL><INDENT>self.assocs = dict((key.lower(), val) for (key, val) in assocs)<EOL><DEDENT>
This constructor is used internally after parsing the header. Instances should generally be created from a factory function, such as parse_headers and its variants.
f3824:c0:m0
@property<EOL><INDENT>def filename_unsafe(self):<DEDENT>
if '<STR_LIT>' in self.assocs:<EOL><INDENT>return self.assocs['<STR_LIT>'].string<EOL><DEDENT>elif '<STR_LIT:filename>' in self.assocs:<EOL><INDENT>return self.assocs['<STR_LIT:filename>']<EOL><DEDENT>elif self.location is not None:<EOL><INDENT>return posixpath.basename(self.location_path.rstrip('<STR_LIT:/>'))<EOL><DEDENT>
The filename from the Content-Disposition header. If a location was passed at instanciation, the basename from that may be used as a fallback. Otherwise, this may be the None value. On safety: This property records the intent of the sender. You shouldn't use this sender-controlled value as a filesystem path, it can be insecure. Serving files with this filename can be dangerous as well, due to a certain browser using the part after the dot for mime-sniffing. Saving it to a database is fine by itself though.
f3824:c0:m1
def filename_sanitized(self, extension, default_filename='<STR_LIT:file>'):
assert extension<EOL>assert extension[<NUM_LIT:0>] != '<STR_LIT:.>'<EOL>assert default_filename<EOL>assert '<STR_LIT:.>' not in default_filename<EOL>extension = '<STR_LIT:.>' + extension<EOL>fname = self.filename_unsafe<EOL>if fname is None:<EOL><INDENT>fname = default_filename<EOL><DEDENT>fname = posixpath.basename(fname)<EOL>fname = os.path.basename(fname)<EOL>fname = fname.lstrip('<STR_LIT:.>')<EOL>if not fname:<EOL><INDENT>fname = default_filename<EOL><DEDENT>if not fname.endswith(extension):<EOL><INDENT>fname = fname + extension<EOL><DEDENT>return fname<EOL>
Returns a filename that is safer to use on the filesystem. The filename will not contain a slash (nor the path separator for the current platform, if different), it will not start with a dot, and it will have the expected extension. No guarantees that makes it "safe enough". No effort is made to remove special characters; using this value blindly might overwrite existing files, etc.
f3824:c0:m3
@property<EOL><INDENT>def is_inline(self):<DEDENT>
return self.disposition.lower() == '<STR_LIT>'<EOL>
If this property is true, the file should be handled inline. Otherwise, and unless your application supports other dispositions than the standard inline and attachment, it should be handled as an attachment.
f3824:c0:m4
def _re_flatten(p):
if '<STR_LIT:(>' not in p: return p<EOL>return re.sub(r'<STR_LIT>',<EOL>lambda m: m.group(<NUM_LIT:0>) if len(m.group(<NUM_LIT:1>)) % <NUM_LIT:2> else m.group(<NUM_LIT:1>) + '<STR_LIT>', p)<EOL>
Turn all capturing groups in a regular expression pattern into non-capturing groups.
f3828:m6
def abort(code=<NUM_LIT>, text='<STR_LIT>'):
raise HTTPError(code, text)<EOL>
Aborts execution and causes a HTTP error.
f3828:m9
def redirect(url, code=None):
if code is None:<EOL><INDENT>code = <NUM_LIT> if request.get('<STR_LIT>') == "<STR_LIT>" else <NUM_LIT><EOL><DEDENT>location = urljoin(request.url, url)<EOL>raise HTTPResponse("<STR_LIT>", status=code, Location=location)<EOL>
Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version.
f3828:m10
def _file_iter_range(fp, offset, bytes, maxread=<NUM_LIT>*<NUM_LIT>):
fp.seek(offset)<EOL>while bytes > <NUM_LIT:0>:<EOL><INDENT>part = fp.read(min(bytes, maxread))<EOL>if not part: break<EOL>bytes -= len(part)<EOL>yield part<EOL><DEDENT>
Yield chunks from a range in a file. No chunk is bigger than maxread.
f3828:m11
def static_file(filename, root, mimetype='<STR_LIT>', download=False):
root = os.path.abspath(root) + os.sep<EOL>filename = os.path.abspath(os.path.join(root, filename.strip('<STR_LIT>')))<EOL>headers = dict()<EOL>if not filename.startswith(root):<EOL><INDENT>return HTTPError(<NUM_LIT>, "<STR_LIT>")<EOL><DEDENT>if not os.path.exists(filename) or not os.path.isfile(filename):<EOL><INDENT>return HTTPError(<NUM_LIT>, "<STR_LIT>")<EOL><DEDENT>if not os.access(filename, os.R_OK):<EOL><INDENT>return HTTPError(<NUM_LIT>, "<STR_LIT>")<EOL><DEDENT>if mimetype == '<STR_LIT>':<EOL><INDENT>mimetype, encoding = mimetypes.guess_type(filename)<EOL>if mimetype: headers['<STR_LIT:Content-Type>'] = mimetype<EOL>if encoding: headers['<STR_LIT>'] = encoding<EOL><DEDENT>elif mimetype:<EOL><INDENT>headers['<STR_LIT:Content-Type>'] = mimetype<EOL><DEDENT>if download:<EOL><INDENT>download = os.path.basename(filename if download == True else download)<EOL>headers['<STR_LIT>'] = '<STR_LIT>' % download<EOL><DEDENT>stats = os.stat(filename)<EOL>headers['<STR_LIT>'] = clen = stats.st_size<EOL>lm = time.strftime("<STR_LIT>", time.gmtime(stats.st_mtime))<EOL>headers['<STR_LIT>'] = lm<EOL>ims = request.environ.get('<STR_LIT>')<EOL>if ims:<EOL><INDENT>ims = parse_date(ims.split("<STR_LIT:;>")[<NUM_LIT:0>].strip())<EOL><DEDENT>if ims is not None and ims >= int(stats.st_mtime):<EOL><INDENT>headers['<STR_LIT>'] = time.strftime("<STR_LIT>", time.gmtime())<EOL>return HTTPResponse(status=<NUM_LIT>, **headers)<EOL><DEDENT>body = '<STR_LIT>' if request.method == '<STR_LIT>' else open(filename, '<STR_LIT:rb>')<EOL>headers["<STR_LIT>"] = "<STR_LIT>"<EOL>ranges = request.environ.get('<STR_LIT>')<EOL>if '<STR_LIT>' in request.environ:<EOL><INDENT>ranges = list(parse_range_header(request.environ['<STR_LIT>'], clen))<EOL>if not ranges:<EOL><INDENT>return HTTPError(<NUM_LIT>, "<STR_LIT>")<EOL><DEDENT>offset, end = ranges[<NUM_LIT:0>]<EOL>headers["<STR_LIT>"] = "<STR_LIT>" % (offset, end-<NUM_LIT:1>, clen)<EOL>headers["<STR_LIT>"] = str(end-offset)<EOL>if body: body = _file_iter_range(body, offset, end-offset)<EOL>return HTTPResponse(body, status=<NUM_LIT>, **headers)<EOL><DEDENT>return HTTPResponse(body, **headers)<EOL>
Open a file in a safe way and return :exc:`HTTPResponse` with status code 200, 305, 401 or 404. Set Content-Type, Content-Encoding, Content-Length and Last-Modified header. Obey If-Modified-Since header and HEAD requests.
f3828:m12
def debug(mode=True):
global DEBUG<EOL>if mode: warnings.simplefilter('<STR_LIT:default>')<EOL>DEBUG = bool(mode)<EOL>
Change the debug level. There is only one debug level supported at the moment.
f3828:m13
def parse_date(ims):
try:<EOL><INDENT>ts = email.utils.parsedate_tz(ims)<EOL>return time.mktime(ts[:<NUM_LIT:8>] + (<NUM_LIT:0>,)) - (ts[<NUM_LIT:9>] or <NUM_LIT:0>) - time.timezone<EOL><DEDENT>except (TypeError, ValueError, IndexError, OverflowError):<EOL><INDENT>return None<EOL><DEDENT>
Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch.
f3828:m14
def parse_auth(header):
try:<EOL><INDENT>method, data = header.split(None, <NUM_LIT:1>)<EOL>if method.lower() == '<STR_LIT>':<EOL><INDENT>user, pwd = touni(base64.b64decode(tob(data))).split('<STR_LIT::>',<NUM_LIT:1>)<EOL>return user, pwd<EOL><DEDENT><DEDENT>except (KeyError, ValueError):<EOL><INDENT>return None<EOL><DEDENT>
Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
f3828:m15
def parse_range_header(header, maxlen=<NUM_LIT:0>):
if not header or header[:<NUM_LIT:6>] != '<STR_LIT>': return<EOL>ranges = [r.split('<STR_LIT:->', <NUM_LIT:1>) for r in header[<NUM_LIT:6>:].split('<STR_LIT:U+002C>') if '<STR_LIT:->' in r]<EOL>for start, end in ranges:<EOL><INDENT>try:<EOL><INDENT>if not start: <EOL><INDENT>start, end = max(<NUM_LIT:0>, maxlen-int(end)), maxlen<EOL><DEDENT>elif not end: <EOL><INDENT>start, end = int(start), maxlen<EOL><DEDENT>else: <EOL><INDENT>start, end = int(start), min(int(end)+<NUM_LIT:1>, maxlen)<EOL><DEDENT>if <NUM_LIT:0> <= start < end <= maxlen:<EOL><INDENT>yield start, end<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>
Yield (start, end) ranges parsed from a HTTP Range header. Skip unsatisfiable ranges. The end index is non-inclusive.
f3828:m16
def _lscmp(a, b):
return not sum(<NUM_LIT:0> if x==y else <NUM_LIT:1> for x, y in zip(a, b)) and len(a) == len(b)<EOL>
Compares two strings in a cryptographically safe way: Runtime is not affected by length of common prefix.
f3828:m18
def cookie_encode(data, key):
msg = base64.b64encode(pickle.dumps(data, -<NUM_LIT:1>))<EOL>sig = base64.b64encode(hmac.new(tob(key), msg).digest())<EOL>return tob('<STR_LIT:!>') + sig + tob('<STR_LIT:?>') + msg<EOL>
Encode and sign a pickle-able object. Return a (byte) string
f3828:m19
def cookie_decode(data, key):
data = tob(data)<EOL>if cookie_is_encoded(data):<EOL><INDENT>sig, msg = data.split(tob('<STR_LIT:?>'), <NUM_LIT:1>)<EOL>if _lscmp(sig[<NUM_LIT:1>:], base64.b64encode(hmac.new(tob(key), msg).digest())):<EOL><INDENT>return pickle.loads(base64.b64decode(msg))<EOL><DEDENT><DEDENT>return None<EOL>
Verify and decode an encoded string. Return an object or None.
f3828:m20
def cookie_is_encoded(data):
return bool(data.startswith(tob('<STR_LIT:!>')) and tob('<STR_LIT:?>') in data)<EOL>
Return True if the argument looks like a encoded cookie.
f3828:m21
def html_escape(string):
return string.replace('<STR_LIT:&>','<STR_LIT>').replace('<STR_LIT:<>','<STR_LIT>').replace('<STR_LIT:>>','<STR_LIT>').replace('<STR_LIT:">','<STR_LIT>').replace("<STR_LIT:'>",'<STR_LIT>')<EOL>
Escape HTML special characters ``&<>`` and quotes ``'"``.
f3828:m22
def html_quote(string):
return '<STR_LIT>' % html_escape(string).replace('<STR_LIT:\n>','<STR_LIT>').replace('<STR_LIT:\r>','<STR_LIT>').replace('<STR_LIT:\t>','<STR_LIT>')<EOL>
Escape and quote a string to be used as an HTTP attribute.
f3828:m23
def yieldroutes(func):
import inspect <EOL>path = '<STR_LIT:/>' + func.__name__.replace('<STR_LIT>','<STR_LIT:/>').lstrip('<STR_LIT:/>')<EOL>spec = inspect.getargspec(func)<EOL>argc = len(spec[<NUM_LIT:0>]) - len(spec[<NUM_LIT:3>] or [])<EOL>path += ('<STR_LIT>' * argc) % tuple(spec[<NUM_LIT:0>][:argc])<EOL>yield path<EOL>for arg in spec[<NUM_LIT:0>][argc:]:<EOL><INDENT>path += '<STR_LIT>' % arg<EOL>yield path<EOL><DEDENT>
Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example:: a() -> '/a' b(x, y) -> '/b/:x/:y' c(x, y=5) -> '/c/:x' and '/c/:x/:y' d(x=5, y=6) -> '/d' and '/d/:x' and '/d/:x/:y'
f3828:m24
def path_shift(script_name, path_info, shift=<NUM_LIT:1>):
if shift == <NUM_LIT:0>: return script_name, path_info<EOL>pathlist = path_info.strip('<STR_LIT:/>').split('<STR_LIT:/>')<EOL>scriptlist = script_name.strip('<STR_LIT:/>').split('<STR_LIT:/>')<EOL>if pathlist and pathlist[<NUM_LIT:0>] == '<STR_LIT>': pathlist = []<EOL>if scriptlist and scriptlist[<NUM_LIT:0>] == '<STR_LIT>': scriptlist = []<EOL>if shift > <NUM_LIT:0> and shift <= len(pathlist):<EOL><INDENT>moved = pathlist[:shift]<EOL>scriptlist = scriptlist + moved<EOL>pathlist = pathlist[shift:]<EOL><DEDENT>elif shift < <NUM_LIT:0> and shift >= -len(scriptlist):<EOL><INDENT>moved = scriptlist[shift:]<EOL>pathlist = moved + pathlist<EOL>scriptlist = scriptlist[:shift]<EOL><DEDENT>else:<EOL><INDENT>empty = '<STR_LIT>' if shift < <NUM_LIT:0> else '<STR_LIT>'<EOL>raise AssertionError("<STR_LIT>" % empty)<EOL><DEDENT>new_script_name = '<STR_LIT:/>' + '<STR_LIT:/>'.join(scriptlist)<EOL>new_path_info = '<STR_LIT:/>' + '<STR_LIT:/>'.join(pathlist)<EOL>if path_info.endswith('<STR_LIT:/>') and pathlist: new_path_info += '<STR_LIT:/>'<EOL>return new_script_name, new_path_info<EOL>
Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change the shift direction. (default: 1)
f3828:m25
def auth_basic(check, realm="<STR_LIT>", text="<STR_LIT>"):
def decorator(func):<EOL><INDENT>def wrapper(*a, **ka):<EOL><INDENT>user, password = request.auth or (None, None)<EOL>if user is None or not check(user, password):<EOL><INDENT>err = HTTPError(<NUM_LIT>, text)<EOL>err.add_header('<STR_LIT>', '<STR_LIT>' % realm)<EOL>return err<EOL><DEDENT>return func(*a, **ka)<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL>
Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter.
f3828:m26
def make_default_app_wrapper(name):
@functools.wraps(getattr(Bottle, name))<EOL>def wrapper(*a, **ka):<EOL><INDENT>return getattr(app(), name)(*a, **ka)<EOL><DEDENT>return wrapper<EOL>
Return a callable that relays calls to the current default app.
f3828:m27
def load(target, **namespace):
module, target = target.split("<STR_LIT::>", <NUM_LIT:1>) if '<STR_LIT::>' in target else (target, None)<EOL>if module not in sys.modules: __import__(module)<EOL>if not target: return sys.modules[module]<EOL>if target.isalnum(): return getattr(sys.modules[module], target)<EOL>package_name = module.split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>namespace[package_name] = sys.modules[package_name]<EOL>return eval('<STR_LIT>' % (module, target), namespace)<EOL>
Import a module or fetch an object from a module. * ``package.module`` returns `module` as a module object. * ``pack.mod:name`` returns the module variable `name` from `pack.mod`. * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result. The last form accepts not only function calls, but any type of expression. Keyword arguments passed to this function are available as local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``
f3828:m28
def load_app(target):
global NORUN; NORUN, nr_old = True, NORUN<EOL>try:<EOL><INDENT>tmp = default_app.push() <EOL>rv = load(target) <EOL>return rv if callable(rv) else tmp<EOL><DEDENT>finally:<EOL><INDENT>default_app.remove(tmp) <EOL>NORUN = nr_old<EOL><DEDENT>
Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See :func:`load` for the target parameter.
f3828:m29
def run(app=None, server='<STR_LIT>', host='<STR_LIT:127.0.0.1>', port=<NUM_LIT>,<EOL>interval=<NUM_LIT:1>, reloader=False, quiet=False, plugins=None,<EOL>debug=False, **kargs):
if NORUN: return<EOL>if reloader and not os.environ.get('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>lockfile = None<EOL>fd, lockfile = tempfile.mkstemp(prefix='<STR_LIT>', suffix='<STR_LIT>')<EOL>os.close(fd) <EOL>while os.path.exists(lockfile):<EOL><INDENT>args = [sys.executable] + sys.argv<EOL>environ = os.environ.copy()<EOL>environ['<STR_LIT>'] = '<STR_LIT:true>'<EOL>environ['<STR_LIT>'] = lockfile<EOL>p = subprocess.Popen(args, env=environ)<EOL>while p.poll() is None: <EOL><INDENT>os.utime(lockfile, None) <EOL>time.sleep(interval)<EOL><DEDENT>if p.poll() != <NUM_LIT:3>:<EOL><INDENT>if os.path.exists(lockfile): os.unlink(lockfile)<EOL>sys.exit(p.poll())<EOL><DEDENT><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT>finally:<EOL><INDENT>if os.path.exists(lockfile):<EOL><INDENT>os.unlink(lockfile)<EOL><DEDENT><DEDENT>return<EOL><DEDENT>try:<EOL><INDENT>_debug(debug)<EOL>app = app or default_app()<EOL>if isinstance(app, basestring):<EOL><INDENT>app = load_app(app)<EOL><DEDENT>if not callable(app):<EOL><INDENT>raise ValueError("<STR_LIT>" % app)<EOL><DEDENT>for plugin in plugins or []:<EOL><INDENT>app.install(plugin)<EOL><DEDENT>if server in server_names:<EOL><INDENT>server = server_names.get(server)<EOL><DEDENT>if isinstance(server, basestring):<EOL><INDENT>server = load(server)<EOL><DEDENT>if isinstance(server, type):<EOL><INDENT>server = server(host=host, port=port, **kargs)<EOL><DEDENT>if not isinstance(server, ServerAdapter):<EOL><INDENT>raise ValueError("<STR_LIT>" % server)<EOL><DEDENT>server.quiet = server.quiet or quiet<EOL>if not server.quiet:<EOL><INDENT>_stderr("<STR_LIT>" % (__version__, repr(server)))<EOL>_stderr("<STR_LIT>" % (server.host, server.port))<EOL>_stderr("<STR_LIT>")<EOL><DEDENT>if reloader:<EOL><INDENT>lockfile = os.environ.get('<STR_LIT>')<EOL>bgcheck = FileCheckerThread(lockfile, interval)<EOL>with bgcheck:<EOL><INDENT>server.run(app)<EOL><DEDENT>if bgcheck.status == '<STR_LIT>':<EOL><INDENT>sys.exit(<NUM_LIT:3>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>server.run(app)<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT>except (SystemExit, MemoryError):<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>if not reloader: raise<EOL>if not getattr(server, '<STR_LIT>', quiet):<EOL><INDENT>print_exc()<EOL><DEDENT>time.sleep(interval)<EOL>sys.exit(<NUM_LIT:3>)<EOL><DEDENT>
Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`) :param server: Server adapter to use. See :data:`server_names` keys for valid names or pass a :class:`ServerAdapter` subclass. (default: `wsgiref`) :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on all interfaces including the external one. (default: 127.0.0.1) :param port: Server port to bind to. Values below 1024 require root privileges. (default: 8080) :param reloader: Start auto-reloading server? (default: False) :param interval: Auto-reloader interval in seconds (default: 1) :param quiet: Suppress output to stdout and stderr? (default: False) :param options: Options passed to the server adapter.
f3828:m30
def template(*args, **kwargs):
tpl = args[<NUM_LIT:0>] if args else None<EOL>adapter = kwargs.pop('<STR_LIT>', SimpleTemplate)<EOL>lookup = kwargs.pop('<STR_LIT>', TEMPLATE_PATH)<EOL>tplid = (id(lookup), tpl)<EOL>if tplid not in TEMPLATES or DEBUG:<EOL><INDENT>settings = kwargs.pop('<STR_LIT>', {})<EOL>if isinstance(tpl, adapter):<EOL><INDENT>TEMPLATES[tplid] = tpl<EOL>if settings: TEMPLATES[tplid].prepare(**settings)<EOL><DEDENT>elif "<STR_LIT:\n>" in tpl or "<STR_LIT:{>" in tpl or "<STR_LIT:%>" in tpl or '<STR_LIT:$>' in tpl:<EOL><INDENT>TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings)<EOL><DEDENT>else:<EOL><INDENT>TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings)<EOL><DEDENT><DEDENT>if not TEMPLATES[tplid]:<EOL><INDENT>abort(<NUM_LIT>, '<STR_LIT>' % tpl)<EOL><DEDENT>for dictarg in args[<NUM_LIT:1>:]: kwargs.update(dictarg)<EOL>return TEMPLATES[tplid].render(kwargs)<EOL>
Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments).
f3828:m31
def view(tpl_name, **defaults):
def decorator(func):<EOL><INDENT>@functools.wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>result = func(*args, **kwargs)<EOL>if isinstance(result, (dict, DictMixin)):<EOL><INDENT>tplvars = defaults.copy()<EOL>tplvars.update(result)<EOL>return template(tpl_name, **tplvars)<EOL><DEDENT>elif result is None:<EOL><INDENT>return template(tpl_name, defaults)<EOL><DEDENT>return result<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL>
Decorator: renders a template for a handler. The handler can control its behavior like that: - return a dict of template vars to fill out the template - return something other than a dict and the view decorator will not process the template, but return the handler result as is. This includes returning a HTTPResponse(dict) to get, for instance, JSON with autojson or other castfilters.
f3828:m32
def add_filter(self, name, func):
self.filters[name] = func<EOL>
Add a filter. The provided function is called with the configuration string as parameter and must return a (regexp, to_python, to_url) tuple. The first element is a string, the last two are callables or None.
f3828:c9:m1
def add(self, rule, method, target, name=None):
anons = <NUM_LIT:0> <EOL>keys = [] <EOL>pattern = '<STR_LIT>' <EOL>filters = [] <EOL>builder = [] <EOL>is_static = True<EOL>for key, mode, conf in self._itertokens(rule):<EOL><INDENT>if mode:<EOL><INDENT>is_static = False<EOL>if mode == '<STR_LIT:default>': mode = self.default_filter<EOL>mask, in_filter, out_filter = self.filters[mode](conf)<EOL>if not key:<EOL><INDENT>pattern += '<STR_LIT>' % mask<EOL>key = '<STR_LIT>' % anons<EOL>anons += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>pattern += '<STR_LIT>' % (key, mask)<EOL>keys.append(key)<EOL><DEDENT>if in_filter: filters.append((key, in_filter))<EOL>builder.append((key, out_filter or str))<EOL><DEDENT>elif key:<EOL><INDENT>pattern += re.escape(key)<EOL>builder.append((None, key))<EOL><DEDENT><DEDENT>self.builder[rule] = builder<EOL>if name: self.builder[name] = builder<EOL>if is_static and not self.strict_order:<EOL><INDENT>group = self.static.setdefault(self.build(rule), {})<EOL>group[method] = (target, None)<EOL>return<EOL><DEDENT>try:<EOL><INDENT>re_pattern = re.compile('<STR_LIT>' % pattern)<EOL>re_match = re_pattern.match<EOL><DEDENT>except re.error:<EOL><INDENT>raise RouteSyntaxError("<STR_LIT>" % (rule, _e()))<EOL><DEDENT>if filters:<EOL><INDENT>def getargs(path):<EOL><INDENT>url_args = re_match(path).groupdict()<EOL>for name, wildcard_filter in filters:<EOL><INDENT>try:<EOL><INDENT>url_args[name] = wildcard_filter(url_args[name])<EOL><DEDENT>except ValueError:<EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT><DEDENT>return url_args<EOL><DEDENT><DEDENT>elif re_pattern.groupindex:<EOL><INDENT>def getargs(path):<EOL><INDENT>return re_match(path).groupdict()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>getargs = None<EOL><DEDENT>flatpat = _re_flatten(pattern)<EOL>if flatpat in self._groups:<EOL><INDENT>group = self._groups[flatpat]<EOL>if method in group:<EOL><INDENT>if DEBUG:<EOL><INDENT>msg = '<STR_LIT>'<EOL>warnings.warn(msg % (method, rule), RuntimeWarning)<EOL><DEDENT><DEDENT>self._groups[flatpat][method] = (target, getargs)<EOL>return<EOL><DEDENT>mdict = self._groups[flatpat] = {method: (target, getargs)}<EOL>try:<EOL><INDENT>combined = '<STR_LIT>' % (self.dynamic[-<NUM_LIT:1>][<NUM_LIT:0>].pattern, flatpat)<EOL>self.dynamic[-<NUM_LIT:1>] = (re.compile(combined), self.dynamic[-<NUM_LIT:1>][<NUM_LIT:1>])<EOL>self.dynamic[-<NUM_LIT:1>][<NUM_LIT:1>].append(mdict)<EOL><DEDENT>except (AssertionError, IndexError): <EOL><INDENT>self.dynamic.append((re.compile('<STR_LIT>' % flatpat), [mdict]))<EOL><DEDENT>
Add a new rule or replace the target for an existing rule.
f3828:c9:m3
def build(self, _name, *anons, **query):
builder = self.builder.get(_name)<EOL>if not builder: raise RouteBuildError("<STR_LIT>", _name)<EOL>try:<EOL><INDENT>for i, value in enumerate(anons): query['<STR_LIT>'%i] = value<EOL>url = '<STR_LIT>'.join([f(query.pop(n)) if n else f for (n,f) in builder])<EOL>return url if not query else url+'<STR_LIT:?>'+urlencode(query)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise RouteBuildError('<STR_LIT>' % _e().args[<NUM_LIT:0>])<EOL><DEDENT>
Build an URL by filling the wildcards in a rule.
f3828:c9:m4
def match(self, environ):
path, targets, urlargs = environ['<STR_LIT>'] or '<STR_LIT:/>', None, {}<EOL>if path in self.static:<EOL><INDENT>targets = self.static[path]<EOL><DEDENT>else:<EOL><INDENT>for combined, rules in self.dynamic:<EOL><INDENT>match = combined.match(path)<EOL>if not match: continue<EOL>targets = rules[match.lastindex - <NUM_LIT:1>]<EOL>break<EOL><DEDENT><DEDENT>if not targets:<EOL><INDENT>raise HTTPError(<NUM_LIT>, "<STR_LIT>" + repr(environ['<STR_LIT>']))<EOL><DEDENT>method = environ['<STR_LIT>'].upper()<EOL>if method in targets:<EOL><INDENT>target, getargs = targets[method]<EOL><DEDENT>elif method == '<STR_LIT>' and '<STR_LIT:GET>' in targets:<EOL><INDENT>target, getargs = targets['<STR_LIT:GET>']<EOL><DEDENT>elif '<STR_LIT>' in targets:<EOL><INDENT>target, getargs = targets['<STR_LIT>'] <EOL><DEDENT>else:<EOL><INDENT>allowed = [verb for verb in targets if verb != '<STR_LIT>']<EOL>if '<STR_LIT:GET>' in allowed and '<STR_LIT>' not in allowed:<EOL><INDENT>allowed.append('<STR_LIT>')<EOL><DEDENT>raise HTTPError(<NUM_LIT>, "<STR_LIT>", Allow="<STR_LIT:U+002C>".join(allowed))<EOL><DEDENT>return target, getargs(path) if getargs else {}<EOL>
Return a (target, url_agrs) tuple or raise HTTPError(400/404/405).
f3828:c9:m5
@cached_property<EOL><INDENT>def call(self):<DEDENT>
return self._make_callback()<EOL>
The route callback with all plugins applied. This property is created on demand and then cached to speed up subsequent requests.
f3828:c10:m2
def reset(self):
self.__dict__.pop('<STR_LIT>', None)<EOL>
Forget any cached values. The next time :attr:`call` is accessed, all plugins are re-applied.
f3828:c10:m3
def prepare(self):
self.call<EOL>
Do all on-demand work immediately (useful for debugging).
f3828:c10:m4
def all_plugins(self):
unique = set()<EOL>for p in reversed(self.app.plugins + self.plugins):<EOL><INDENT>if True in self.skiplist: break<EOL>name = getattr(p, '<STR_LIT:name>', False)<EOL>if name and (name in self.skiplist or name in unique): continue<EOL>if p in self.skiplist or type(p) in self.skiplist: continue<EOL>if name: unique.add(name)<EOL>yield p<EOL><DEDENT>
Yield all Plugins affecting this route.
f3828:c10:m6
def mount(self, prefix, app, **options):
if isinstance(app, basestring):<EOL><INDENT>depr('<STR_LIT>', True) <EOL><DEDENT>segments = [p for p in prefix.split('<STR_LIT:/>') if p]<EOL>if not segments: raise ValueError('<STR_LIT>')<EOL>path_depth = len(segments)<EOL>def mountpoint_wrapper():<EOL><INDENT>try:<EOL><INDENT>request.path_shift(path_depth)<EOL>rs = HTTPResponse([])<EOL>def start_response(status, headerlist, exc_info=None):<EOL><INDENT>if exc_info:<EOL><INDENT>try:<EOL><INDENT>_raise(*exc_info)<EOL><DEDENT>finally:<EOL><INDENT>exc_info = None<EOL><DEDENT><DEDENT>rs.status = status<EOL>for name, value in headerlist: rs.add_header(name, value)<EOL>return rs.body.append<EOL><DEDENT>body = app(request.environ, start_response)<EOL>if body and rs.body: body = itertools.chain(rs.body, body)<EOL>rs.body = body or rs.body<EOL>return rs<EOL><DEDENT>finally:<EOL><INDENT>request.path_shift(-path_depth)<EOL><DEDENT><DEDENT>options.setdefault('<STR_LIT>', True)<EOL>options.setdefault('<STR_LIT>', '<STR_LIT>')<EOL>options.setdefault('<STR_LIT>', {'<STR_LIT>': prefix, '<STR_LIT:target>': app})<EOL>options['<STR_LIT>'] = mountpoint_wrapper<EOL>self.route('<STR_LIT>' % '<STR_LIT:/>'.join(segments), **options)<EOL>if not prefix.endswith('<STR_LIT:/>'):<EOL><INDENT>self.route('<STR_LIT:/>' + '<STR_LIT:/>'.join(segments), **options)<EOL><DEDENT>
Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: root_app.mount('/admin/', admin_app) :param prefix: path prefix or `mount-point`. If it ends in a slash, that slash is mandatory. :param app: an instance of :class:`Bottle` or a WSGI application. All other parameters are passed to the underlying :meth:`route` call.
f3828:c11:m1
def merge(self, routes):
if isinstance(routes, Bottle):<EOL><INDENT>routes = routes.routes<EOL><DEDENT>for route in routes:<EOL><INDENT>self.add_route(route)<EOL><DEDENT>
Merge the routes of another :class:`Bottle` application or a list of :class:`Route` objects into this application. The routes keep their 'owner', meaning that the :data:`Route.app` attribute is not changed.
f3828:c11:m2
def install(self, plugin):
if hasattr(plugin, '<STR_LIT>'): plugin.setup(self)<EOL>if not callable(plugin) and not hasattr(plugin, '<STR_LIT>'):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.plugins.append(plugin)<EOL>self.reset()<EOL>return plugin<EOL>
Add a plugin to the list of plugins and prepare it for being applied to all routes of this application. A plugin may be a simple decorator or an object that implements the :class:`Plugin` API.
f3828:c11:m3
def uninstall(self, plugin):
removed, remove = [], plugin<EOL>for i, plugin in list(enumerate(self.plugins))[::-<NUM_LIT:1>]:<EOL><INDENT>if remove is True or remove is plugin or remove is type(plugin)or getattr(plugin, '<STR_LIT:name>', True) == remove:<EOL><INDENT>removed.append(plugin)<EOL>del self.plugins[i]<EOL>if hasattr(plugin, '<STR_LIT>'): plugin.close()<EOL><DEDENT><DEDENT>if removed: self.reset()<EOL>return removed<EOL>
Uninstall plugins. Pass an instance to remove a specific plugin, a type object to remove all plugins that match that type, a string to remove all plugins with a matching ``name`` attribute or ``True`` to remove all plugins. Return the list of removed plugins.
f3828:c11:m4
def run(self, **kwargs):
run(self, **kwargs)<EOL>
Calls :func:`run` with the same parameters.
f3828:c11:m5
def reset(self, route=None):
if route is None: routes = self.routes<EOL>elif isinstance(route, Route): routes = [route]<EOL>else: routes = [self.routes[route]]<EOL>for route in routes: route.reset()<EOL>if DEBUG:<EOL><INDENT>for route in routes: route.prepare()<EOL><DEDENT>self.hooks.trigger('<STR_LIT>')<EOL>
Reset all routes (force plugins to be re-applied) and clear all caches. If an ID or route object is given, only that specific route is affected.
f3828:c11:m6
def close(self):
for plugin in self.plugins:<EOL><INDENT>if hasattr(plugin, '<STR_LIT>'): plugin.close()<EOL><DEDENT>self.stopped = True<EOL>
Close the application and all installed plugins.
f3828:c11:m7
def match(self, environ):
return self.router.match(environ)<EOL>
Search for a matching route and return a (:class:`Route` , urlargs) tuple. The second value is a dictionary with parameters extracted from the URL. Raise :exc:`HTTPError` (404/405) on a non-match.
f3828:c11:m8
def get_url(self, routename, **kargs):
scriptname = request.environ.get('<STR_LIT>', '<STR_LIT>').strip('<STR_LIT:/>') + '<STR_LIT:/>'<EOL>location = self.router.build(routename, **kargs).lstrip('<STR_LIT:/>')<EOL>return urljoin(urljoin('<STR_LIT:/>', scriptname), location)<EOL>
Return a string that matches a named route
f3828:c11:m9
def add_route(self, route):
self.routes.append(route)<EOL>self.router.add(route.rule, route.method, route, name=route.name)<EOL>if DEBUG: route.prepare()<EOL>
Add a route object, but do not change the :data:`Route.app` attribute.
f3828:c11:m10
def route(self, path=None, method='<STR_LIT:GET>', callback=None, name=None,<EOL>apply=None, skip=None, **config):
if callable(path): path, callback = None, path<EOL>plugins = makelist(apply)<EOL>skiplist = makelist(skip)<EOL>def decorator(callback):<EOL><INDENT>if isinstance(callback, basestring): callback = load(callback)<EOL>for rule in makelist(path) or yieldroutes(callback):<EOL><INDENT>for verb in makelist(method):<EOL><INDENT>verb = verb.upper()<EOL>route = Route(self, rule, verb, callback, name=name,<EOL>plugins=plugins, skiplist=skiplist, **config)<EOL>self.add_route(route)<EOL><DEDENT><DEDENT>return callback<EOL><DEDENT>return decorator(callback) if callback else decorator<EOL>
A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name The ``:name`` part is a wildcard. See :class:`Router` for syntax details. :param path: Request path or a list of paths to listen to. If no path is specified, it is automatically generated from the signature of the function. :param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of methods to listen to. (default: `GET`) :param callback: An optional shortcut to avoid the decorator syntax. ``route(..., callback=func)`` equals ``route(...)(func)`` :param name: The name for this route. (default: None) :param apply: A decorator or plugin or a list of plugins. These are applied to the route callback in addition to installed plugins. :param skip: A list of plugins, plugin classes or names. Matching plugins are not installed to this route. ``True`` skips all. Any additional keyword arguments are stored as route-specific configuration and passed to plugins (see :meth:`Plugin.apply`).
f3828:c11:m11
def get(self, path=None, method='<STR_LIT:GET>', **options):
return self.route(path, method, **options)<EOL>
Equals :meth:`route`.
f3828:c11:m12
def post(self, path=None, method='<STR_LIT:POST>', **options):
return self.route(path, method, **options)<EOL>
Equals :meth:`route` with a ``POST`` method parameter.
f3828:c11:m13
def put(self, path=None, method='<STR_LIT>', **options):
return self.route(path, method, **options)<EOL>
Equals :meth:`route` with a ``PUT`` method parameter.
f3828:c11:m14
def delete(self, path=None, method='<STR_LIT>', **options):
return self.route(path, method, **options)<EOL>
Equals :meth:`route` with a ``DELETE`` method parameter.
f3828:c11:m15
def error(self, code=<NUM_LIT>):
def wrapper(handler):<EOL><INDENT>self.error_handler[int(code)] = handler<EOL>return handler<EOL><DEDENT>return wrapper<EOL>
Decorator: Register an output handler for a HTTP error code
f3828:c11:m16
def hook(self, name):
def wrapper(func):<EOL><INDENT>self.hooks.add(name, func)<EOL>return func<EOL><DEDENT>return wrapper<EOL>
Return a decorator that attaches a callback to a hook. Three hooks are currently implemented: - before_request: Executed once before each request - after_request: Executed once after each request - app_reset: Called whenever :meth:`reset` is called.
f3828:c11:m17
def handle(self, path, method='<STR_LIT:GET>'):
depr("<STR_LIT>")<EOL>if isinstance(path, dict):<EOL><INDENT>return self._handle(path)<EOL><DEDENT>return self._handle({'<STR_LIT>': path, '<STR_LIT>': method.upper()})<EOL>
(deprecated) Execute the first matching route callback and return the result. :exc:`HTTPResponse` exceptions are caught and returned. If :attr:`Bottle.catchall` is true, other exceptions are caught as well and returned as :exc:`HTTPError` instances (500).
f3828:c11:m18
def _cast(self, out, peek=None):
<EOL>if not out:<EOL><INDENT>if '<STR_LIT>' not in response:<EOL><INDENT>response['<STR_LIT>'] = <NUM_LIT:0><EOL><DEDENT>return []<EOL><DEDENT>if isinstance(out, (tuple, list))and isinstance(out[<NUM_LIT:0>], (bytes, unicode)):<EOL><INDENT>out = out[<NUM_LIT:0>][<NUM_LIT:0>:<NUM_LIT:0>].join(out) <EOL><DEDENT>if isinstance(out, unicode):<EOL><INDENT>out = out.encode(response.charset)<EOL><DEDENT>if isinstance(out, bytes):<EOL><INDENT>if '<STR_LIT>' not in response:<EOL><INDENT>response['<STR_LIT>'] = len(out)<EOL><DEDENT>return [out]<EOL><DEDENT>if isinstance(out, HTTPError):<EOL><INDENT>out.apply(response)<EOL>out = self.error_handler.get(out.status_code, self.default_error_handler)(out)<EOL>return self._cast(out)<EOL><DEDENT>if isinstance(out, HTTPResponse):<EOL><INDENT>out.apply(response)<EOL>return self._cast(out.body)<EOL><DEDENT>if hasattr(out, '<STR_LIT>'):<EOL><INDENT>if '<STR_LIT>' in request.environ:<EOL><INDENT>return request.environ['<STR_LIT>'](out)<EOL><DEDENT>elif hasattr(out, '<STR_LIT>') or not hasattr(out, '<STR_LIT>'):<EOL><INDENT>return WSGIFileWrapper(out)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>iout = iter(out)<EOL>first = next(iout)<EOL>while not first:<EOL><INDENT>first = next(iout)<EOL><DEDENT><DEDENT>except StopIteration:<EOL><INDENT>return self._cast('<STR_LIT>')<EOL><DEDENT>except HTTPResponse:<EOL><INDENT>first = _e()<EOL><DEDENT>except (KeyboardInterrupt, SystemExit, MemoryError):<EOL><INDENT>raise<EOL><DEDENT>except Exception:<EOL><INDENT>if not self.catchall: raise<EOL>first = HTTPError(<NUM_LIT>, '<STR_LIT>', _e(), format_exc())<EOL><DEDENT>if isinstance(first, HTTPResponse):<EOL><INDENT>return self._cast(first)<EOL><DEDENT>elif isinstance(first, bytes):<EOL><INDENT>new_iter = itertools.chain([first], iout)<EOL><DEDENT>elif isinstance(first, unicode):<EOL><INDENT>encoder = lambda x: x.encode(response.charset)<EOL>new_iter = imap(encoder, itertools.chain([first], iout))<EOL><DEDENT>else:<EOL><INDENT>msg = '<STR_LIT>' % type(first)<EOL>return self._cast(HTTPError(<NUM_LIT>, msg))<EOL><DEDENT>if hasattr(out, '<STR_LIT>'):<EOL><INDENT>new_iter = _closeiter(new_iter, out.close)<EOL><DEDENT>return new_iter<EOL>
Try to convert the parameter into something WSGI compatible and set correct HTTP headers when possible. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, iterable of strings and iterable of unicodes
f3828:c11:m21
def wsgi(self, environ, start_response):
try:<EOL><INDENT>out = self._cast(self._handle(environ))<EOL>if response._status_code in (<NUM_LIT:100>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>)or environ['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>if hasattr(out, '<STR_LIT>'): out.close()<EOL>out = []<EOL><DEDENT>start_response(response._status_line, response.headerlist)<EOL>return out<EOL><DEDENT>except (KeyboardInterrupt, SystemExit, MemoryError):<EOL><INDENT>raise<EOL><DEDENT>except Exception:<EOL><INDENT>if not self.catchall: raise<EOL>err = '<STR_LIT>'% html_escape(environ.get('<STR_LIT>', '<STR_LIT:/>'))<EOL>if DEBUG:<EOL><INDENT>err += '<STR_LIT>''<STR_LIT>'% (html_escape(repr(_e())), html_escape(format_exc()))<EOL><DEDENT>environ['<STR_LIT>'].write(err)<EOL>headers = [('<STR_LIT:Content-Type>', '<STR_LIT>')]<EOL>start_response('<STR_LIT>', headers, sys.exc_info())<EOL>return [tob(err)]<EOL><DEDENT>
The bottle WSGI-interface.
f3828:c11:m22
def __call__(self, environ, start_response):
return self.wsgi(environ, start_response)<EOL>
Each instance of :class:'Bottle' is a WSGI application.
f3828:c11:m23