desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Like for normal object, we link templates with each others'
def linkify_templates(self):
self.hosts.linkify_templates() self.contacts.linkify_templates() self.services.linkify_templates() self.servicedependencies.linkify_templates() self.hostdependencies.linkify_templates() self.timeperiods.linkify_templates() self.hostsextinfo.linkify_templates() self.servicesextinfo.linkif...
'Check if all elements got a good configuration'
def is_correct(self):
logger.info('Running pre-flight check on configuration data...') r = self.conf_is_correct if (self.read_config_silent == 0): logger.info('Checking global parameters...') if (not self.check_error_on_hard_unmanaged_parameters()): r = False logger.error('Check ...
'Indicates if a service holds a duplicate_foreach statement'
def is_duplicate(self):
if getattr(self, 'duplicate_foreach', None): return True else: return False
'For a given host, look for all copy we must create for for_each property :type host: shinken.objects.host.Host :return Service'
def duplicate(self, host):
prop = self.duplicate_foreach.strip().upper() if (prop not in host.customs): return [] duplicates = [] entry = host.customs[prop] not_entry = host.customs.get((('_' + '!') + prop[1:]), '').split(',') not_keys = strip_and_uniq(not_entry) default_value = getattr(self, 'default_value', ...
'Adds and index a template into the `templates` container. This implementation takes into account that a service has two naming attribute: `host_name` and `service_description`. :param tpl: The template to add'
def add_template(self, tpl):
objcls = self.inner_class.my_type name = getattr(tpl, 'name', '') hname = getattr(tpl, 'host_name', '') if ((not name) and (not hname)): mesg = ('a %s template has been defined without name nor host_name%s' % (objcls, self.get_source(tpl))) tpl.configuration_er...
'Adds and index an item into the `items` container. This implementation takes into account that a service has two naming attribute: `host_name` and `service_description`. :param item: The item to add :param index: Flag indicating if the item should be indexed'
def add_item(self, item, index=True):
objcls = self.inner_class.my_type hname = getattr(item, 'host_name', '') hgname = getattr(item, 'hostgroup_name', '') sdesc = getattr(item, 'service_description', '') source = getattr(item, 'imported_from', 'unknown') if source: in_file = (' in %s' % source) else: in_fi...
'For all items and templates inherite properties and custom variables.'
def apply_inheritance(self):
cls = self.inner_class for prop in cls.properties: self.apply_partial_inheritance(prop) for i in itertools.chain(self.items.itervalues(), self.templates.itervalues()): i.get_customs_properties_by_inheritance(0)
'Sets services initial state if required in configuration'
def set_initial_state(self):
for s in self: s.set_initial_state()
'Explodes a service based on a lis of hosts. :param hosts: The hosts container :param s: The base service to explode :param hnames: The host_name list to exlode sevice on'
def explode_services_from_hosts(self, hosts, s, hnames):
duplicate_for_hosts = [] not_hosts = [] for hname in hnames: hname = hname.strip() if hname.startswith('!'): not_hosts.append(hname[1:]) else: duplicate_for_hosts.append(hname) duplicate_for_hosts = list(set(duplicate_for_hosts)) for hname in not_hosts...
'Create a new service based on a host_name and service instance. :param hosts: The hosts items instance. :type hosts: shinken.objects.host.Hosts :param host_name: The host_name to create a new service. :param service: The service to be used as template. :type service: Service :return: ...
def _local_create_service(self, hosts, host_name, service):
h = hosts.find_by_name(host_name.strip()) if h.is_excluded_for(service): return new_s = service.copy() new_s.host_name = host_name new_s.register = 1 if new_s.is_duplicate(): self.add_item(new_s, index=False) else: self.add_item(new_s) return new_s
'Explodes services from templates. All hosts holding the specified templates are bound the service. :param hosts: The hosts container. :type hosts: shinken.objects.host.Hosts :param service: The service to explode. :type service: Service'
def explode_services_from_templates(self, hosts, service):
hname = getattr(service, 'host_name', None) if (not hname): return if is_complex_expr(hname): hnames = self.evaluate_hostgroup_expression(hname.strip(), hosts, hosts.templates, look_in='templates') for name in hnames: self._local_create_service(hosts, name, service) e...
'Explodes services holding a `duplicate_foreach` clause. :param hosts: The hosts container :param s: The service to explode :type s: Service'
def explode_services_duplicates(self, hosts, s):
hname = getattr(s, 'host_name', None) if (hname is None): return h = hosts.find_by_name(hname.strip()) if (h is None): err = ('Error: The hostname %s is unknown for the service %s!' % (hname, s.get_name())) s.configuration_errors.append(err) ret...
'Registers a service into the service groups declared in its `servicegroups` attribute. :param s: The service to register :param servicegroups: The servicegroups container'
def register_service_into_servicegroups(self, s, servicegroups):
if hasattr(s, 'service_description'): sname = s.service_description shname = getattr(s, 'host_name', '') if hasattr(s, 'servicegroups'): if isinstance(s.servicegroups, list): sgs = s.servicegroups else: sgs = s.servicegroups.split(',') ...
'Registers a service dependencies. :param s: The service to register :param servicedependencies: The servicedependencies container'
def register_service_dependencies(self, s, servicedependencies):
sdeps = [d.strip() for d in getattr(s, 'service_dependencies', [])] i = 0 hname = '' for elt in sdeps: if ((i % 2) == 0): hname = elt else: desc = elt if (hasattr(s, 'service_description') and hasattr(s, 'host_name')): if (hname == ''):...
'Explodes services, from host_name, hostgroup_name, and from templetes. :param hosts: The hosts container :param hostgroups: The hostgoups container :param contactgroups: The concactgoups container :param servicegroups: The servicegoups container :param servicedependencies: The servic...
def explode(self, hosts, hostgroups, contactgroups, servicegroups, servicedependencies, triggers):
self.explode_trigger_string_into_triggers(triggers) for t in self.templates.values(): self.explode_contact_groups_into_contacts(t, contactgroups) self.explode_services_from_templates(hosts, t) duplicates = [s.id for s in self if s.is_duplicate()] for id in duplicates: s = self.it...
'Return a copy of the item, but give him a new id'
def copy(self):
cls = self.__class__ i = cls({}) for prop in cls.properties: if hasattr(self, prop): val = getattr(self, prop) setattr(i, prop, val) i.customs = copy(self.customs) if hasattr(self, 'tags'): i.tags = copy(self.tags) if hasattr(self, 'templates'): i....
'Clean useless things not requested once item has been fully initialized&configured. Like temporary attributes such as "imported_from", etc..'
def clean(self):
for name in ('imported_from', 'use', 'plus', 'templates'): try: delattr(self, name) except AttributeError: pass
'Return if the elements is a template'
def is_tpl(self):
return (not getattr(self, 'register', True))
'Fill missing properties if they are missing'
def fill_default(self):
cls = self.__class__ for (prop, entry) in cls.properties.items(): if ((not hasattr(self, prop)) and entry.has_default): setattr(self, prop, entry.default)
'Used to put global values in the sub Class like hosts or services'
def load_global_conf(cls, conf):
for (prop, entry) in conf.properties.items(): if hasattr(conf, prop): for (cls_dest, change_name) in entry.class_inherit: if (cls_dest == cls): value = getattr(conf, prop) if (change_name is None): setattr(cls, prop,...
'Add items into the `items` or `templates` container depending on the is_tpl method result. :param items: The items list to add. :param index_items: Flag indicating if the items should be indexed on the fly.'
def add_items(self, items, index_items):
for i in items: if i.is_tpl(): self.add_template(i) else: self.add_item(i, index_items)
'Cheks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definiton order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has prec...
def manage_conflict(self, item, name):
if item.is_tpl(): existing = self.name_to_template[name] else: existing = self.name_to_item[name] existing_prio = getattr(existing, 'definition_order', existing.properties['definition_order'].default) item_prio = getattr(item, 'definition_order', item.properties['definition_order'].defau...
'Adds and index a template into the `templates` container. :param tpl: The template to add'
def add_template(self, tpl):
tpl = self.index_template(tpl) self.templates[tpl.id] = tpl
'Indexes a template by `name` into the `name_to_template` dictionnary. :param tpl: The template to index'
def index_template(self, tpl):
objcls = self.inner_class.my_type name = getattr(tpl, 'name', '') if (not name): mesg = ('a %s template has been defined without name%s%s' % (objcls, tpl.imported_from, self.get_source(tpl))) tpl.configuration_errors.append(mesg) elif (name in self.name_to_template):...
'Removes and unindex a template from the `templates` container. :param tpl: The template to remove'
def remove_template(self, tpl):
try: del self.templates[tpl.id] except KeyError: pass self.unindex_template(tpl)
'Unindex a template from the `templates` container. :param tpl: The template to unindex'
def unindex_template(self, tpl):
name = getattr(tpl, 'name', '') try: del self.name_to_template[name] except KeyError: pass
'Adds an item into our containers, and index it depending on the `index` flag. :param item: The item to add :param index: Flag indicating if the item should be indexed'
def add_item(self, item, index=True):
name_property = getattr(self.__class__, 'name_property', None) if ((index is True) and name_property): item = self.index_item(item) self.items[item.id] = item
'Removes (and un-index) an item from our containers. :param item: The item to be removed. :type item: Item # or subclass of'
def remove_item(self, item):
self.unindex_item(item) try: self.items.pop(item.id) except KeyError: safe_print(('ERROR: Internal Issue, this case should not happen %s ' % item)) pass
'Indexes an item into our `name_to_item` dictionary. If an object holding the same item\'s name/key already exists in the index then the conflict is managed by the `manage_conflict` method. :param item: The item to index :param name: The optional name to use to index the item'
def index_item(self, item):
name_property = getattr(self.__class__, 'name_property', None) name = getattr(item, name_property, '') if (not name): objcls = self.inner_class.my_type mesg = ('a %s item has been defined without %s%s' % (objcls, name_property, self.get_source(item))) item.config...
'Unindex an item from our name_to_item dict. :param item: The item to unindex'
def unindex_item(self, item):
name_property = getattr(self.__class__, 'name_property', None) if (name_property is None): return self.name_to_item.pop(getattr(item, name_property, ''), None)
'Remove useless templates (& properties) of our items otherwise we could get errors on config.is_correct()'
def remove_templates(self):
del self.templates
'Request to remove the unnecessary attributes/others from our items'
def clean(self):
for i in self: i.clean() Item.clean(self)
'For all items and templates inherite properties and custom variables.'
def apply_inheritance(self):
cls = self.inner_class for prop in cls.properties: self.apply_partial_inheritance(prop) for i in itertools.chain(self.items.itervalues(), self.templates.itervalues()): i.get_customs_properties_by_inheritance(0)
'Find loop in dependencies. For now, used with the following attributes : :(self, parents): host dependencies from host object :(host_name, dependent_host_name): host dependencies from hostdependencies object :(service_description, dependent_service_description): service dependencies from servicedependencies...
def no_loop_in_parents(self, attr1, attr2, templates=False):
r = True parents = Graph() elts_lst = self if templates: elts_lst = self.templates.values() for item in elts_lst: if (attr1 == 'self'): obj = item else: obj = getattr(item, attr1, None) if (obj is not None): if isinstance(obj, list)...
'Sets the object\'s initial state, state_id, and output attributes if initial other than default values are wanted. The allowed states have to be given in the mapping dictionnary, following the pattern below: "o": { "state": "OK", "state_id": 0 :param mapping: The mapping describing the allowed states'
def set_initial_state(self, mapping):
init_state = getattr(self, 'initial_state', '') if init_state: if (init_state in mapping): self.state = mapping[init_state]['state'] self.state_id = mapping[init_state]['state_id'] else: err = ('invalid initial_state: %s, should be one of ...
'Returns a status string for business rules based items formatted using business_rule_output_template attribute as template. The template may embed output formatting for itself, and for its child (dependant) itmes. Childs format string is expanded into the $( and )$, using the string between brackets as format string. ...
def get_business_rule_output(self):
got_business_rule = getattr(self, 'got_business_rule', False) if ((got_business_rule is False) or (self.business_rule is None)): return '' output_template = self.business_rule_output_template if (not output_template): return '' m = MacroResolver() elts = re.findall('\\$\\((.*)\\)...
'Rebuild the possible reference a schedulingitem can have'
def rebuild_ref(self):
for g in (self.comments, self.downtimes): for o in g: o.ref = self
'Check whether this host should have the passed service be "excluded" or "not included". An host can define service_includes and/or service_excludes directive to either white-list-only or black-list some services from itself. :type service: shinken.objects.service.Service'
def is_excluded_for(self, service):
return self.is_excluded_for_sdesc(service.service_description, service.is_tpl())
'Check whether this host should have the passed service *description* be "excluded" or "not included".'
def is_excluded_for_sdesc(self, sdesc, is_tpl=False):
if ((not is_tpl) and hasattr(self, 'service_includes')): incl = False for d in self.service_includes: try: fct = get_exclude_match_expr(d) if fct(sdesc): incl = True except Exception as e: self.configuration_...
'Sets hosts initial state if required in configuration'
def set_initial_state(self):
for h in self: h.set_initial_state()
'Create the database connection'
def connect_database(self):
self.db = sqlite3.connect(self.db_path) self.db_cursor = self.db.cursor()
'Just run the query'
def execute_query(self, query):
logger.debug("[SqliteDB] Info: I run query '%s'", query) self.db_cursor.execute(query) self.db.commit()
'Dummy function, only useful for checks'
def set_type_active(self):
pass
'Dummy function, only useful for checks'
def set_type_passive(self):
pass
'Mix the env and the environment variables into a new local env dict. Note: We cannot just update the global os.environ because this would effect all other checks.'
def get_local_environnement(self):
local_env = os.environ.copy() for p in self.env: local_env[p] = self.env[p].encode('utf8') return local_env
'Start this action command. The command will be executed in a subprocess.'
def execute(self):
self.status = 'launched' self.check_time = time.time() self.wait_time = 0.0001 self.last_poll = self.check_time self.local_env = self.get_local_environnement() self.stdoutdata = '' self.stderrdata = '' return self.execute__()
'Copy all attributes listed in \'only_copy_prop\' from `self` to `new_i`.'
def copy_shell__(self, new_i):
for prop in only_copy_prop: setattr(new_i, prop, getattr(self, prop)) return new_i
'`default`: default value to be used if this property is not set. If default is None, this property is required. `class_inherit`: List of 2-tuples, (Service, \'blabla\'): must set this property to the Service class with name blabla. if (Service, None): must set this property to the Service class with same name `unmanag...
def __init__(self, default=none_object, class_inherit=None, unmanaged=False, help='', no_slots=False, fill_brok=None, conf_send_preparation=None, brok_transformation=None, retention=False, retention_preparation=None, to_send=False, override=False, managed=True, split_on_coma=True, merging='uniq'):
self.default = default self.has_default = (default is not none_object) self.required = (not self.has_default) self.class_inherit = (class_inherit or []) self.help = (help or '') self.unmanaged = unmanaged self.no_slots = no_slots self.fill_brok = (fill_brok or []) self.conf_send_prep...
'Dictionary of values. If elts_prop is not None, must be a Property subclass All dict values will be casted as elts_prop values when pythonized elts_prop = Property of dict members'
def __init__(self, elts_prop=None, *args, **kwargs):
super(DictProp, self).__init__(*args, **kwargs) if ((elts_prop is not None) and (not issubclass(elts_prop, Property))): raise TypeError('DictProp constructor only accept Propertysub-classes as elts_prop parameter') if (elts_prop is not None): self.elts_prop = elts_prop()...
'i.e: val = "192.168.10.24:445" NOTE: port is optional'
def pythonize(self, val):
val = unique_value(val) m = re.match('^([^:]*)(?::(\\d+))?$', val) if (m is None): raise ValueError addr = {'address': m.group(1)} if (m.group(2) is not None): addr['port'] = int(m.group(2)) return addr
'Compensate a system time change of difference for all hosts/services/checks/notifs'
def compensate_system_time_change(self, difference):
logger.warning('A system time change of %d has been detected. Compensating...', difference) self.program_start = max(0, (self.program_start + difference)) if (not hasattr(self.sched, 'conf')): return for h in self.sched.hosts: h.compensate_system_time_change(di...
'Setup a new conf received from a Master arbiter.'
def setup_new_conf(self):
conf = self.new_conf if (not conf): return conf = cPickle.loads(conf) self.new_conf = None self.cur_conf = conf self.conf = conf if self.aggressive_memory_management: free_memory() for arb in self.conf.arbiters: if ((arb.address, arb.port) == (self.host, self.port...
'Returns the daemons list defined in our conf for the given type'
def get_daemons(self, daemon_type):
return getattr(self.conf, (daemon_type + 's'), None)
'Create the database connection TODO: finish (begin :) ) error catch and conf parameters... Import to catch exception'
def connect_database(self):
self.db = MySQLdb.connect(host=self.host, user=self.user, passwd=self.password, db=self.database, port=self.port) self.db.set_character_set(self.character_set) self.db_cursor = self.db.cursor() self.db_cursor.execute(('SET NAMES %s;' % self.character_set)) self.db_cursor.execute(('SET CHARA...
'Just run the query TODO: finish catch'
def execute_query(self, query, do_debug=False):
if do_debug: logger.debug('[MysqlDB]I run query %s', query) try: self.db_cursor.execute(query) self.db.commit() return True except IntegrityError as exp: logger.warning('[MysqlDB] A query raised an integrity error: %s, %s', query, exp)...
'Add a new route or replace the target for an existing route.'
def add(self, rule, method, target, name=None):
if (rule in self.routes): self.routes[rule][method.upper()] = target else: self.routes[rule] = {method.upper(): target} self.rules.append(rule) if (self.static or self.dynamic): (self.static, self.dynamic) = ({}, {}) if name: self.named[name] = (rule, None...
'Return a string that matches a named route. Use keyword arguments to fill out named wildcards. Remaining arguments are appended as a query string. Raises RouteBuildError or KeyError.'
def build(self, _name, *anon, **args):
if (_name not in self.named): raise RouteBuildError('No route with that name.', _name) (rule, pairs) = self.named[_name] if (not pairs): token = self.syntax.split(rule) parts = [p.replace('\\:', ':') for p in token[::3]] names = token[1::3] if (len(parts) ...
'Return a (target, url_agrs) tuple or raise HTTPError(404/405).'
def match(self, environ):
(targets, urlargs) = self._match_path(environ) if (not targets): raise HTTPError(404, ('Not found: ' + repr(environ['PATH_INFO']))) method = environ['REQUEST_METHOD'].upper() if (method in targets): return (targets[method], urlargs) if ((method == 'HEAD') and ('GET' in targets)...
'Optimized PATH_INFO matcher.'
def _match_path(self, environ):
path = (environ['PATH_INFO'] or '/') match = self.static.get(path) if match: return (match, {}) for (combined, rules) in self.dynamic: match = combined.match(path) if (not match): continue (gpat, match) = rules[(match.lastindex - 1)] return (match, (gp...
'Prepare static and dynamic search structures.'
def _compile(self):
self.static = {} self.dynamic = [] def fpat_sub(m): return (m.group(0) if (len(m.group(1)) % 2) else (m.group(1) + '(?:')) for rule in self.rules: target = self.routes[rule] if (not self.syntax.search(rule)): self.static[rule.replace('\\:', ':')] = target ...
'Return a regular expression with named groups for each wildcard.'
def _compile_pattern(self, rule):
out = '' for (i, part) in enumerate(self.syntax.split(rule)): if ((i % 3) == 0): out += re.escape(part.replace('\\:', ':')) elif ((i % 3) == 1): out += (('(?P<%s>' % part) if part else '(?:') else: out += ('%s)' % (part or '[^/]+')) return re.compi...
'Create a new bottle instance. You usually don\'t do that. Use `bottle.app.push()` instead.'
def __init__(self, catchall=True, autojson=True, config=None):
self.routes = [] self.router = Router() self.ccache = {} self.plugins = [] self.mounts = {} self.error_handler = {} self.catchall = catchall self.config = (config or {}) self.serve = True self.hooks = self.install(HooksPlugin()) if autojson: self.install(JSONPlugin())...
'Mount an application to a specific URL prefix. The prefix is added to SCRIPT_PATH and removed from PATH_INFO before the sub-application is called.:param app: an instance of :class:`Bottle`.:param prefix: path prefix used as a mount-point. All other parameters are passed to the underlying :meth:`route` call.'
def mount(self, app, prefix, **options):
if (not isinstance(app, Bottle)): raise TypeError('Only Bottle instances are supported for now.') prefix = '/'.join(filter(None, prefix.split('/'))) if (not prefix): raise TypeError('Empty prefix. Perhaps you want a merge()?') for other in self.mounts:...
'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.'
def install(self, plugin):
if hasattr(plugin, 'setup'): plugin.setup(self) if ((not callable(plugin)) and (not hasattr(plugin, 'apply'))): raise TypeError('Plugins must be callable or implement .apply()') self.plugins.append(plugin) self.reset() return plugin
'Uninstall plugins. Pass an instance to remove a specific plugin. Pass a type object to remove all plugins that match that type. Subclasses are not removed. Pass a string to remove all plugins with a matching ``name`` attribute. Pass ``True`` to remove all plugins. The list of affected plugins is returned.'
def uninstall(self, plugin):
(removed, remove) = ([], plugin) for (i, plugin) in list(enumerate(self.plugins))[::(-1)]: if ((remove is True) or (remove is plugin) or (remove is type(plugin)) or (getattr(plugin, 'name', True) == remove)): removed.append(plugin) del self.plugins[i] if hasattr(plugi...
'Reset all routes (force plugins to be re-applied) and clear all caches. If an ID is given, only that specific route is affected.'
def reset(self, id=None):
if (id is None): self.ccache.clear() else: self.ccache.pop(id, None) if DEBUG: for route in self.routes: if (route['id'] not in self.ccache): self.ccache[route['id']] = self._build_callback(route)
'Close the application and all installed plugins.'
def close(self):
for plugin in self.plugins: if hasattr(plugin, 'close'): plugin.close() self.stopped = True
'(deprecated) Search for a matching route and return a (callback, urlargs) tuple. The first element is the associated route callback with plugins applied. The second value is a dictionary with parameters extracted from the URL. The :class:`Router` raises :exc:`HTTPError` (404/405) on a non-match.'
def match(self, environ):
depr('This method will change semantics in 0.10.') return self._match(environ)
'Apply plugins to a route and return a new callable.'
def _build_callback(self, config):
wrapped = config['callback'] plugins = (self.plugins + config['apply']) skip = config['skip'] try: for plugin in reversed(plugins): if (True in skip): break if ((plugin in skip) or (type(plugin) in skip)): continue if (getattr(p...
'Return a string that matches a named route'
def get_url(self, routename, **kargs):
scriptname = (request.environ.get('SCRIPT_NAME', '').strip('/') + '/') location = self.router.build(routename, **kargs).lstrip('/') return urljoin(urljoin('/', scriptname), location)
'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 ...
def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config):
if callable(path): (path, callback) = (None, path) plugins = makelist(apply) skiplist = makelist(skip) def decorator(callback): for rule in (makelist(path) or yieldroutes(callback)): for verb in makelist(method): verb = verb.upper() cfg = dict(...
'Equals :meth:`route`.'
def get(self, path=None, method='GET', **options):
return self.route(path, method, **options)
'Equals :meth:`route` with a ``POST`` method parameter.'
def post(self, path=None, method='POST', **options):
return self.route(path, method, **options)
'Equals :meth:`route` with a ``PUT`` method parameter.'
def put(self, path=None, method='PUT', **options):
return self.route(path, method, **options)
'Equals :meth:`route` with a ``DELETE`` method parameter.'
def delete(self, path=None, method='DELETE', **options):
return self.route(path, method, **options)
'Decorator: Register an output handler for a HTTP error code'
def error(self, code=500):
def wrapper(handler): self.error_handler[int(code)] = handler return handler return wrapper
'Return a decorator that attaches a callback to a hook.'
def hook(self, name):
def wrapper(func): self.hooks.add(name, func) return func return wrapper
'(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).'
def handle(self, path, method='GET'):
depr('This method will change semantics in 0.10. Try to avoid it.') if isinstance(path, dict): return self._handle(path) return self._handle({'PATH_INFO': path, 'REQUEST_METHOD': method.upper()})
'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'
def _cast(self, out, request, response, peek=None):
if (not out): response['Content-Length'] = 0 return [] if (isinstance(out, (tuple, list)) and isinstance(out[0], (bytes, unicode))): out = out[0][0:0].join(out) if isinstance(out, unicode): out = out.encode(response.charset) if isinstance(out, bytes): response['Co...
'The bottle WSGI-interface.'
def wsgi(self, environ, start_response):
try: environ['bottle.app'] = self if ('HTTP_X_FORWARDED_PROTO' in environ): environ['wsgi.url_scheme'] = environ['HTTP_X_FORWARDED_PROTO'] request.bind(environ) response.bind() out = self._cast(self._handle(environ), request, response) if ((response.status...
'Wrap a WSGI environ dictionary.'
def __init__(self, environ):
self.environ = environ environ['bottle.request'] = self
'The value of ``PATH_INFO`` with exactly one prefixed slash (to fix broken clients and avoid the "empty path" edge case).'
@property def path(self):
return ('/' + self.environ.get('PATH_INFO', '').lstrip('/'))
'The ``REQUEST_METHOD`` value as an uppercase string.'
@property def method(self):
return self.environ.get('REQUEST_METHOD', 'GET').upper()
'A :class:`WSGIHeaderDict` that provides case-insensitive access to HTTP request headers.'
@DictProperty('environ', 'bottle.request.headers', read_only=True) def headers(self):
return WSGIHeaderDict(self.environ)
'Cookies parsed into a dictionary. Signed cookies are NOT decoded. Use :meth:`get_cookie` if you expect signed cookies.'
@DictProperty('environ', 'bottle.request.cookies', read_only=True) def cookies(self):
raw_dict = SimpleCookie(self.environ.get('HTTP_COOKIE', '')) cookies = {} for cookie in raw_dict.itervalues(): cookies[cookie.key] = cookie.value return cookies
'Return the content of a cookie. To read a `Signed Cookie`, the `secret` must match the one used to create the cookie (see :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing cookie or wrong signature), return a default value.'
def get_cookie(self, key, default=None, secret=None):
value = self.cookies.get(key) if (secret and value): dec = cookie_decode(value, secret) return (dec[1] if (dec and (dec[0] == key)) else default) return (value or default)
'The :attr:`query_string` parsed into a :class:`MultiDict`. These values are sometimes called "URL arguments" or "GET parameters", but not to be confused with "URL wildcards" as they are provided by the :class:`Router`.'
@DictProperty('environ', 'bottle.request.query', read_only=True) def query(self):
data = parse_qs(self.query_string, keep_blank_values=True) get = self.environ['bottle.get'] = MultiDict() for (key, values) in data.iteritems(): for value in values: get[key] = value return get
'Form values parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The result is returned as a :class:`MultiDict`. All keys and values are strings. File uploads are stored separately in :attr:`files`.'
@DictProperty('environ', 'bottle.request.forms', read_only=True) def forms(self):
forms = MultiDict() for (name, item) in self.POST.iterallitems(): if (not hasattr(item, 'filename')): forms[name] = item return forms
'A :class:`MultiDict` with the combined values of :attr:`query` and :attr:`forms`. File uploads are stored in :attr:`files`.'
@DictProperty('environ', 'bottle.request.params', read_only=True) def params(self):
params = MultiDict() for (key, value) in self.query.iterallitems(): params[key] = value for (key, value) in self.forms.iterallitems(): params[key] = value return params
'File uploads parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The values are instances of :class:`cgi.FieldStorage`. The most important attributes are: filename The filename, if specified; otherwise None; this is the client side filename, *not* the file name on which it is stored...
@DictProperty('environ', 'bottle.request.files', read_only=True) def files(self):
files = MultiDict() for (name, item) in self.POST.iterallitems(): if hasattr(item, 'filename'): files[name] = item return files
'If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion.'
@DictProperty('environ', 'bottle.request.json', read_only=True) def json(self):
if ((self.environ.get('CONTENT_TYPE') == 'application/json') and (0 < self.content_length < self.MEMFILE_MAX)): return json_loads(self.body.read(self.MEMFILE_MAX)) return None
'The HTTP request body as a seek-able file-like object. Depending on :attr:`MEMFILE_MAX`, this is either a temporary file or a :class:`io.BytesIO` instance. Accessing this property for the first time reads and replaces the ``wsgi.input`` environ variable. Subsequent accesses just do a `seek(0)` on the file object.'
@property def body(self):
self._body.seek(0) return self._body
'The values of :attr:`forms` and :attr:`files` combined into a single :class:`MultiDict`. Values are either strings (form values) or instances of :class:`cgi.FieldStorage` (file uploads).'
@DictProperty('environ', 'bottle.request.post', read_only=True) def POST(self):
post = MultiDict() safe_env = {'QUERY_STRING': ''} for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'): if (key in self.environ): safe_env[key] = self.environ[key] if NCTextIOWrapper: fb = NCTextIOWrapper(self.body, encoding='ISO-8859-1', newline='\n') else: ...
'Alias for :attr:`cookies` (deprecated).'
@property def COOKIES(self):
depr('BaseRequest.COOKIES was renamed to BaseRequest.cookies (lowercase).') return self.cookies
'The full request URI including hostname and scheme. If your app lives behind a reverse proxy or load balancer and you get confusing results, make sure that the ``X-Forwarded-Host`` header is set correctly.'
@property def url(self):
return self.urlparts.geturl()
'The :attr:`url` string as an :class:`urlparse.SplitResult` tuple. The tuple contains (scheme, host, path, query_string and fragment), but the fragment is always empty because it is not visible to the server.'
@DictProperty('environ', 'bottle.request.urlparts', read_only=True) def urlparts(self):
env = self.environ http = env.get('wsgi.url_scheme', 'http') host = (env.get('HTTP_X_FORWARDED_HOST') or env.get('HTTP_HOST')) if (not host): host = env.get('SERVER_NAME', '127.0.0.1') port = env.get('SERVER_PORT') if (port and (port != ('80' if (http == 'http') else '443'))): ...
'Request path including :attr:`script_name` (if present).'
@property def fullpath(self):
return urljoin(self.script_name, self.path.lstrip('/'))
'The raw :attr:`query` part of the URL (everything in between ``?`` and ``#``) as a string.'
@property def query_string(self):
return self.environ.get('QUERY_STRING', '')
'The initial portion of the URL\'s `path` that was removed by a higher level (server or routing middleware) before the application was called. This property returns an empty string, or a path with leading and tailing slashes.'
@property def script_name(self):
script_name = self.environ.get('SCRIPT_NAME', '').strip('/') return ((('/' + script_name) + '/') if script_name else '/')
'Shift path segments from :attr:`path` to :attr:`script_name` and vice versa.:param shift: The number of path segments to shift. May be negative to change the shift direction. (default: 1)'
def path_shift(self, shift=1):
script = self.environ.get('SCRIPT_NAME', '/') (self['SCRIPT_NAME'], self['PATH_INFO']) = path_shift(script, self.path, shift)