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><... | 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'.
... | 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 KeyboardInterru... | 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 wit... | 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')
... | 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... | 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... | 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]<E... | 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... | 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>') = No... | 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><INDE... | 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... | 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... | 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 s... | 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>mo... | 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 directorie... | 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 f... | 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>repl... | 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>setat... | 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,
... | 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... | 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... | 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... | 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 t... | 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.
Val... | 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><IND... | 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_f... | 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... | 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.... | 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... | 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.c... | 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.s... | 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 = en... | 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>... | 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... | 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><DE... | 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 th... | 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(fn... | 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... | 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>r... | 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(en... | 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[<NU... | 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' ... | 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_... | 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.... | 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><DEDE... | 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:.>')[... | 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 funct... | 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.cop... | 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 ... | 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>TEMPLA... | 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:<EO... | 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.
... | 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,... | 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(... | 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_L... | 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(na... | 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 = H... | 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 :cla... | 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>')... | 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><INDEN... | 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 o... | 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 isinst... | 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>r... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.