index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
70,235
slacker
delete
null
def delete(self, reminder): return self.post('reminders.delete', data={'reminder': reminder})
(self, reminder)
70,237
slacker
info
null
def info(self, reminder): return self.get('reminders.info', params={'reminder': reminder})
(self, reminder)
70,238
slacker
list
null
def list(self): return self.get('reminders.list')
(self)
70,240
slacker
Response
null
class Response(object): def __init__(self, body): self.raw = body self.body = json.loads(body) self.successful = self.body['ok'] self.error = self.body.get('error') def __str__(self): return json.dumps(self.body)
(body)
70,241
slacker
__init__
null
def __init__(self, body): self.raw = body self.body = json.loads(body) self.successful = self.body['ok'] self.error = self.body.get('error')
(self, body)
70,242
slacker
__str__
null
def __str__(self): return json.dumps(self.body)
(self)
70,243
slacker
Search
null
class Search(BaseAPI): def all(self, query, sort=None, sort_dir=None, highlight=None, count=None, page=None): return self.get('search.all', params={ 'query': query, 'sort': sort, 'sort_dir': sort_dir, 'highlight': highlight, 'count': count, 'page': page }) def files(self, query, sort=None, sort_dir=None, highlight=None, count=None, page=None): return self.get('search.files', params={ 'query': query, 'sort': sort, 'sort_dir': sort_dir, 'highlight': highlight, 'count': count, 'page': page }) def messages(self, query, sort=None, sort_dir=None, highlight=None, count=None, page=None): return self.get('search.messages', params={ 'query': query, 'sort': sort, 'sort_dir': sort_dir, 'highlight': highlight, 'count': count, 'page': page })
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
70,248
slacker
all
null
def all(self, query, sort=None, sort_dir=None, highlight=None, count=None, page=None): return self.get('search.all', params={ 'query': query, 'sort': sort, 'sort_dir': sort_dir, 'highlight': highlight, 'count': count, 'page': page })
(self, query, sort=None, sort_dir=None, highlight=None, count=None, page=None)
70,249
slacker
files
null
def files(self, query, sort=None, sort_dir=None, highlight=None, count=None, page=None): return self.get('search.files', params={ 'query': query, 'sort': sort, 'sort_dir': sort_dir, 'highlight': highlight, 'count': count, 'page': page })
(self, query, sort=None, sort_dir=None, highlight=None, count=None, page=None)
70,251
slacker
messages
null
def messages(self, query, sort=None, sort_dir=None, highlight=None, count=None, page=None): return self.get('search.messages', params={ 'query': query, 'sort': sort, 'sort_dir': sort_dir, 'highlight': highlight, 'count': count, 'page': page })
(self, query, sort=None, sort_dir=None, highlight=None, count=None, page=None)
70,253
slacker
Slacker
null
class Slacker(object): oauth = OAuth(timeout=DEFAULT_TIMEOUT) def __init__(self, token, incoming_webhook_url=None, timeout=DEFAULT_TIMEOUT, http_proxy=None, https_proxy=None, session=None, rate_limit_retries=DEFAULT_RETRIES): proxies = self.__create_proxies(http_proxy, https_proxy) api_args = { 'token': token, 'timeout': timeout, 'proxies': proxies, 'session': session, 'rate_limit_retries': rate_limit_retries, } self.im = IM(**api_args) self.api = API(**api_args) self.dnd = DND(**api_args) self.rtm = RTM(**api_args) self.apps = Apps(**api_args) self.auth = Auth(**api_args) self.bots = Bots(**api_args) self.chat = Chat(**api_args) self.dialog = Dialog(**api_args) self.team = Team(**api_args) self.pins = Pins(**api_args) self.mpim = MPIM(**api_args) self.users = Users(**api_args) self.files = Files(**api_args) self.stars = Stars(**api_args) self.emoji = Emoji(**api_args) self.search = Search(**api_args) self.groups = Groups(**api_args) self.channels = Channels(**api_args) self.presence = Presence(**api_args) self.reminders = Reminders(**api_args) self.migration = Migration(**api_args) self.reactions = Reactions(**api_args) self.idpgroups = IDPGroups(**api_args) self.usergroups = UserGroups(**api_args) self.conversations = Conversations(**api_args) self.incomingwebhook = IncomingWebhook(url=incoming_webhook_url, timeout=timeout, proxies=proxies) def __create_proxies(self, http_proxy=None, https_proxy=None): proxies = dict() if http_proxy: proxies['http'] = http_proxy if https_proxy: proxies['https'] = https_proxy return proxies
(token, incoming_webhook_url=None, timeout=10, http_proxy=None, https_proxy=None, session=None, rate_limit_retries=0)
70,254
slacker
__create_proxies
null
def __create_proxies(self, http_proxy=None, https_proxy=None): proxies = dict() if http_proxy: proxies['http'] = http_proxy if https_proxy: proxies['https'] = https_proxy return proxies
(self, http_proxy=None, https_proxy=None)
70,255
slacker
__init__
null
def __init__(self, token, incoming_webhook_url=None, timeout=DEFAULT_TIMEOUT, http_proxy=None, https_proxy=None, session=None, rate_limit_retries=DEFAULT_RETRIES): proxies = self.__create_proxies(http_proxy, https_proxy) api_args = { 'token': token, 'timeout': timeout, 'proxies': proxies, 'session': session, 'rate_limit_retries': rate_limit_retries, } self.im = IM(**api_args) self.api = API(**api_args) self.dnd = DND(**api_args) self.rtm = RTM(**api_args) self.apps = Apps(**api_args) self.auth = Auth(**api_args) self.bots = Bots(**api_args) self.chat = Chat(**api_args) self.dialog = Dialog(**api_args) self.team = Team(**api_args) self.pins = Pins(**api_args) self.mpim = MPIM(**api_args) self.users = Users(**api_args) self.files = Files(**api_args) self.stars = Stars(**api_args) self.emoji = Emoji(**api_args) self.search = Search(**api_args) self.groups = Groups(**api_args) self.channels = Channels(**api_args) self.presence = Presence(**api_args) self.reminders = Reminders(**api_args) self.migration = Migration(**api_args) self.reactions = Reactions(**api_args) self.idpgroups = IDPGroups(**api_args) self.usergroups = UserGroups(**api_args) self.conversations = Conversations(**api_args) self.incomingwebhook = IncomingWebhook(url=incoming_webhook_url, timeout=timeout, proxies=proxies)
(self, token, incoming_webhook_url=None, timeout=10, http_proxy=None, https_proxy=None, session=None, rate_limit_retries=0)
70,256
slacker
Stars
null
class Stars(BaseAPI): def add(self, file_=None, file_comment=None, channel=None, timestamp=None): assert file_ or file_comment or channel return self.post('stars.add', data={ 'file': file_, 'file_comment': file_comment, 'channel': channel, 'timestamp': timestamp }) def list(self, user=None, count=None, page=None): return self.get('stars.list', params={'user': user, 'count': count, 'page': page}) def remove(self, file_=None, file_comment=None, channel=None, timestamp=None): assert file_ or file_comment or channel return self.post('stars.remove', data={ 'file': file_, 'file_comment': file_comment, 'channel': channel, 'timestamp': timestamp })
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
70,261
slacker
add
null
def add(self, file_=None, file_comment=None, channel=None, timestamp=None): assert file_ or file_comment or channel return self.post('stars.add', data={ 'file': file_, 'file_comment': file_comment, 'channel': channel, 'timestamp': timestamp })
(self, file_=None, file_comment=None, channel=None, timestamp=None)
70,263
slacker
list
null
def list(self, user=None, count=None, page=None): return self.get('stars.list', params={'user': user, 'count': count, 'page': page})
(self, user=None, count=None, page=None)
70,265
slacker
remove
null
def remove(self, file_=None, file_comment=None, channel=None, timestamp=None): assert file_ or file_comment or channel return self.post('stars.remove', data={ 'file': file_, 'file_comment': file_comment, 'channel': channel, 'timestamp': timestamp })
(self, file_=None, file_comment=None, channel=None, timestamp=None)
70,266
slacker
Team
null
class Team(BaseAPI): def __init__(self, *args, **kwargs): super(Team, self).__init__(*args, **kwargs) self._profile = TeamProfile(*args, **kwargs) @property def profile(self): return self._profile def info(self): return self.get('team.info') def access_logs(self, count=None, page=None, before=None): return self.get('team.accessLogs', params={ 'count': count, 'page': page, 'before': before }) def integration_logs(self, service_id=None, app_id=None, user=None, change_type=None, count=None, page=None): return self.get('team.integrationLogs', params={ 'service_id': service_id, 'app_id': app_id, 'user': user, 'change_type': change_type, 'count': count, 'page': page, }) def billable_info(self, user=None): return self.get('team.billableInfo', params={'user': user})
(*args, **kwargs)
70,267
slacker
__init__
null
def __init__(self, *args, **kwargs): super(Team, self).__init__(*args, **kwargs) self._profile = TeamProfile(*args, **kwargs)
(self, *args, **kwargs)
70,271
slacker
access_logs
null
def access_logs(self, count=None, page=None, before=None): return self.get('team.accessLogs', params={ 'count': count, 'page': page, 'before': before })
(self, count=None, page=None, before=None)
70,272
slacker
billable_info
null
def billable_info(self, user=None): return self.get('team.billableInfo', params={'user': user})
(self, user=None)
70,274
slacker
info
null
def info(self): return self.get('team.info')
(self)
70,275
slacker
integration_logs
null
def integration_logs(self, service_id=None, app_id=None, user=None, change_type=None, count=None, page=None): return self.get('team.integrationLogs', params={ 'service_id': service_id, 'app_id': app_id, 'user': user, 'change_type': change_type, 'count': count, 'page': page, })
(self, service_id=None, app_id=None, user=None, change_type=None, count=None, page=None)
70,277
slacker
TeamProfile
null
class TeamProfile(BaseAPI): def get(self, visibility=None): return super(TeamProfile, self).get( 'team.profile.get', params={'visibility': visibility} )
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
70,282
slacker
get
null
def get(self, visibility=None): return super(TeamProfile, self).get( 'team.profile.get', params={'visibility': visibility} )
(self, visibility=None)
70,284
slacker
UserGroups
null
class UserGroups(BaseAPI): def __init__(self, *args, **kwargs): super(UserGroups, self).__init__(*args, **kwargs) self._users = UserGroupsUsers(*args, **kwargs) @property def users(self): return self._users def list(self, include_disabled=None, include_count=None, include_users=None): if isinstance(include_disabled, bool): include_disabled = int(include_disabled) if isinstance(include_count, bool): include_count = int(include_count) if isinstance(include_users, bool): include_users = int(include_users) return self.get('usergroups.list', params={ 'include_disabled': include_disabled, 'include_count': include_count, 'include_users': include_users, }) def create(self, name, handle=None, description=None, channels=None, include_count=None): if isinstance(channels, (tuple, list)): channels = ','.join(channels) if isinstance(include_count, bool): include_count = int(include_count) return self.post('usergroups.create', data={ 'name': name, 'handle': handle, 'description': description, 'channels': channels, 'include_count': include_count, }) def update(self, usergroup, name=None, handle=None, description=None, channels=None, include_count=None): if isinstance(channels, (tuple, list)): channels = ','.join(channels) if isinstance(include_count, bool): include_count = int(include_count) return self.post('usergroups.update', data={ 'usergroup': usergroup, 'name': name, 'handle': handle, 'description': description, 'channels': channels, 'include_count': include_count, }) def disable(self, usergroup, include_count=None): if isinstance(include_count, bool): include_count = int(include_count) return self.post('usergroups.disable', data={ 'usergroup': usergroup, 'include_count': include_count, }) def enable(self, usergroup, include_count=None): if isinstance(include_count, bool): include_count = int(include_count) return self.post('usergroups.enable', data={ 'usergroup': usergroup, 'include_count': include_count, })
(*args, **kwargs)
70,285
slacker
__init__
null
def __init__(self, *args, **kwargs): super(UserGroups, self).__init__(*args, **kwargs) self._users = UserGroupsUsers(*args, **kwargs)
(self, *args, **kwargs)
70,289
slacker
create
null
def create(self, name, handle=None, description=None, channels=None, include_count=None): if isinstance(channels, (tuple, list)): channels = ','.join(channels) if isinstance(include_count, bool): include_count = int(include_count) return self.post('usergroups.create', data={ 'name': name, 'handle': handle, 'description': description, 'channels': channels, 'include_count': include_count, })
(self, name, handle=None, description=None, channels=None, include_count=None)
70,290
slacker
disable
null
def disable(self, usergroup, include_count=None): if isinstance(include_count, bool): include_count = int(include_count) return self.post('usergroups.disable', data={ 'usergroup': usergroup, 'include_count': include_count, })
(self, usergroup, include_count=None)
70,291
slacker
enable
null
def enable(self, usergroup, include_count=None): if isinstance(include_count, bool): include_count = int(include_count) return self.post('usergroups.enable', data={ 'usergroup': usergroup, 'include_count': include_count, })
(self, usergroup, include_count=None)
70,293
slacker
list
null
def list(self, include_disabled=None, include_count=None, include_users=None): if isinstance(include_disabled, bool): include_disabled = int(include_disabled) if isinstance(include_count, bool): include_count = int(include_count) if isinstance(include_users, bool): include_users = int(include_users) return self.get('usergroups.list', params={ 'include_disabled': include_disabled, 'include_count': include_count, 'include_users': include_users, })
(self, include_disabled=None, include_count=None, include_users=None)
70,295
slacker
update
null
def update(self, usergroup, name=None, handle=None, description=None, channels=None, include_count=None): if isinstance(channels, (tuple, list)): channels = ','.join(channels) if isinstance(include_count, bool): include_count = int(include_count) return self.post('usergroups.update', data={ 'usergroup': usergroup, 'name': name, 'handle': handle, 'description': description, 'channels': channels, 'include_count': include_count, })
(self, usergroup, name=None, handle=None, description=None, channels=None, include_count=None)
70,296
slacker
UserGroupsUsers
null
class UserGroupsUsers(BaseAPI): def list(self, usergroup, include_disabled=None): if isinstance(include_disabled, bool): include_disabled = int(include_disabled) return self.get('usergroups.users.list', params={ 'usergroup': usergroup, 'include_disabled': include_disabled, }) def update(self, usergroup, users, include_count=None): if isinstance(users, (tuple, list)): users = ','.join(users) if isinstance(include_count, bool): include_count = int(include_count) return self.post('usergroups.users.update', data={ 'usergroup': usergroup, 'users': users, 'include_count': include_count, })
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
70,302
slacker
list
null
def list(self, usergroup, include_disabled=None): if isinstance(include_disabled, bool): include_disabled = int(include_disabled) return self.get('usergroups.users.list', params={ 'usergroup': usergroup, 'include_disabled': include_disabled, })
(self, usergroup, include_disabled=None)
70,304
slacker
update
null
def update(self, usergroup, users, include_count=None): if isinstance(users, (tuple, list)): users = ','.join(users) if isinstance(include_count, bool): include_count = int(include_count) return self.post('usergroups.users.update', data={ 'usergroup': usergroup, 'users': users, 'include_count': include_count, })
(self, usergroup, users, include_count=None)
70,305
slacker
Users
null
class Users(BaseAPI): def __init__(self, *args, **kwargs): super(Users, self).__init__(*args, **kwargs) self._profile = UsersProfile(*args, **kwargs) self._admin = UsersAdmin(*args, **kwargs) @property def profile(self): return self._profile @property def admin(self): return self._admin def info(self, user, include_locale=False): return self.get('users.info', params={'user': user, 'include_locale': include_locale}) def list(self, presence=False): return self.get('users.list', params={'presence': int(presence)}) def identity(self): return self.get('users.identity') def set_active(self): return self.post('users.setActive') def get_presence(self, user): return self.get('users.getPresence', params={'user': user}) def set_presence(self, presence): return self.post('users.setPresence', data={'presence': presence}) def get_user_id(self, user_name): members = self.list().body['members'] return get_item_id_by_name(members, user_name)
(*args, **kwargs)
70,306
slacker
__init__
null
def __init__(self, *args, **kwargs): super(Users, self).__init__(*args, **kwargs) self._profile = UsersProfile(*args, **kwargs) self._admin = UsersAdmin(*args, **kwargs)
(self, *args, **kwargs)
70,311
slacker
get_presence
null
def get_presence(self, user): return self.get('users.getPresence', params={'user': user})
(self, user)
70,312
slacker
get_user_id
null
def get_user_id(self, user_name): members = self.list().body['members'] return get_item_id_by_name(members, user_name)
(self, user_name)
70,313
slacker
identity
null
def identity(self): return self.get('users.identity')
(self)
70,314
slacker
info
null
def info(self, user, include_locale=False): return self.get('users.info', params={'user': user, 'include_locale': include_locale})
(self, user, include_locale=False)
70,315
slacker
list
null
def list(self, presence=False): return self.get('users.list', params={'presence': int(presence)})
(self, presence=False)
70,317
slacker
set_active
null
def set_active(self): return self.post('users.setActive')
(self)
70,318
slacker
set_presence
null
def set_presence(self, presence): return self.post('users.setPresence', data={'presence': presence})
(self, presence)
70,319
slacker
UsersAdmin
null
class UsersAdmin(BaseAPI): def invite(self, email, channels=None, first_name=None, last_name=None, resend=True): return self.post('users.admin.invite', params={ 'email': email, 'channels': channels, 'first_name': first_name, 'last_name': last_name, 'resend': resend })
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
70,325
slacker
invite
null
def invite(self, email, channels=None, first_name=None, last_name=None, resend=True): return self.post('users.admin.invite', params={ 'email': email, 'channels': channels, 'first_name': first_name, 'last_name': last_name, 'resend': resend })
(self, email, channels=None, first_name=None, last_name=None, resend=True)
70,327
slacker
UsersProfile
null
class UsersProfile(BaseAPI): def get(self, user=None, include_labels=False): return super(UsersProfile, self).get( 'users.profile.get', params={'user': user, 'include_labels': int(include_labels)} ) def set(self, user=None, profile=None, name=None, value=None): return self.post('users.profile.set', data={ 'user': user, 'profile': profile, 'name': name, 'value': value })
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
70,332
slacker
get
null
def get(self, user=None, include_labels=False): return super(UsersProfile, self).get( 'users.profile.get', params={'user': user, 'include_labels': int(include_labels)} )
(self, user=None, include_labels=False)
70,334
slacker
set
null
def set(self, user=None, profile=None, name=None, value=None): return self.post('users.profile.set', data={ 'user': user, 'profile': profile, 'name': name, 'value': value })
(self, user=None, profile=None, name=None, value=None)
70,335
slacker.utilities
get_api_url
Returns API URL for the given method. :param method: Method name :type method: str :returns: API URL for the given method :rtype: str
def get_api_url(method): """ Returns API URL for the given method. :param method: Method name :type method: str :returns: API URL for the given method :rtype: str """ return 'https://slack.com/api/{}'.format(method)
(method)
70,336
slacker.utilities
get_item_id_by_name
null
def get_item_id_by_name(list_dict, key_name): for d in list_dict: if d['name'] == key_name: return d['id']
(list_dict, key_name)
70,341
oslo_middleware.basic_auth
BasicAuthMiddleware
Middleware which performs HTTP basic authentication on requests
class BasicAuthMiddleware(base.ConfigurableMiddleware): """Middleware which performs HTTP basic authentication on requests""" def __init__(self, application, conf=None): super().__init__(application, conf) self.auth_file = cfg.CONF.oslo_middleware.http_basic_auth_user_file validate_auth_file(self.auth_file) def format_exception(self, e): result = {'error': {'message': str(e), 'code': 401}} headers = [('Content-Type', 'application/json')] return webob.Response(content_type='application/json', status_code=401, json_body=result, headerlist=headers) @webob.dec.wsgify def __call__(self, req): try: token = parse_header(req.environ) username, password = parse_token(token) req.environ.update(authenticate( self.auth_file, username, password)) return self.application except Exception as e: response = self.format_exception(e) return self.process_response(response)
(application, conf=None)
70,342
oslo_middleware.basic_auth
__init__
null
def __init__(self, application, conf=None): super().__init__(application, conf) self.auth_file = cfg.CONF.oslo_middleware.http_basic_auth_user_file validate_auth_file(self.auth_file)
(self, application, conf=None)
70,343
oslo_middleware.base
_conf_get
null
def _conf_get(self, key, group="oslo_middleware"): if key in self.conf: # Validate value type self.oslo_conf.set_override(key, self.conf[key], group=group) return getattr(getattr(self.oslo_conf, group), key)
(self, key, group='oslo_middleware')
70,344
oslo_middleware.basic_auth
format_exception
null
def format_exception(self, e): result = {'error': {'message': str(e), 'code': 401}} headers = [('Content-Type', 'application/json')] return webob.Response(content_type='application/json', status_code=401, json_body=result, headerlist=headers)
(self, e)
70,345
oslo_middleware.base
process_request
Called on each request. If this returns None, the next application down the stack will be executed. If it returns a response then that response will be returned and execution will stop here.
@staticmethod def process_request(req): """Called on each request. If this returns None, the next application down the stack will be executed. If it returns a response then that response will be returned and execution will stop here. """ return None
(req)
70,346
oslo_middleware.base
process_response
Do whatever you'd like to the response.
@staticmethod def process_response(response, request=None): """Do whatever you'd like to the response.""" return response
(response, request=None)
70,347
oslo_middleware.cors
CORS
CORS Middleware. This middleware allows a WSGI app to serve CORS headers for multiple configured domains. For more information, see http://www.w3.org/TR/cors/
class CORS(base.ConfigurableMiddleware): """CORS Middleware. This middleware allows a WSGI app to serve CORS headers for multiple configured domains. For more information, see http://www.w3.org/TR/cors/ """ simple_headers = [ 'Accept', 'Accept-Language', 'Content-Type', 'Cache-Control', 'Content-Language', 'Expires', 'Last-Modified', 'Pragma' ] def __init__(self, application, *args, **kwargs): super(CORS, self).__init__(application, *args, **kwargs) # Begin constructing our configuration hash. self.allowed_origins = {} self._init_conf() def sanitize(csv_list): try: return [str.strip(x) for x in csv_list.split(',')] except Exception: return None @classmethod def factory(cls, global_conf, **local_conf): """factory method for paste.deploy allowed_origin: Protocol, host, and port for the allowed origin. allow_credentials: Whether to permit credentials. expose_headers: A list of headers to expose. max_age: Maximum cache duration. allow_methods: List of HTTP methods to permit. allow_headers: List of HTTP headers to permit from the client. """ if ('allowed_origin' not in local_conf and 'oslo_config_project' not in local_conf): raise TypeError("allowed_origin or oslo_config_project " "is required") return super(CORS, cls).factory(global_conf, **local_conf) def _init_conf(self): '''Initialize this middleware from an oslo.config instance.''' # First, check the configuration and register global options. self.oslo_conf.register_opts(CORS_OPTS, 'cors') allowed_origin = self._conf_get('allowed_origin', 'cors') allow_credentials = self._conf_get('allow_credentials', 'cors') expose_headers = self._conf_get('expose_headers', 'cors') max_age = self._conf_get('max_age', 'cors') allow_methods = self._conf_get('allow_methods', 'cors') allow_headers = self._conf_get('allow_headers', 'cors') # Clone our original CORS_OPTS, and set the defaults to whatever is # set in the global conf instance. This is done explicitly (instead # of **kwargs), since we don't accidentally want to catch # allowed_origin. subgroup_opts = copy.deepcopy(CORS_OPTS) cfg.set_defaults(subgroup_opts, allow_credentials=allow_credentials, expose_headers=expose_headers, max_age=max_age, allow_methods=allow_methods, allow_headers=allow_headers) # If the default configuration contains an allowed_origin, don't # forget to register that. self.add_origin(allowed_origin=allowed_origin, allow_credentials=allow_credentials, expose_headers=expose_headers, max_age=max_age, allow_methods=allow_methods, allow_headers=allow_headers) # Iterate through all the loaded config sections, looking for ones # prefixed with 'cors.' for section in self.oslo_conf.list_all_sections(): if section.startswith('cors.'): debtcollector.deprecate('Multiple configuration blocks are ' 'deprecated and will be removed in ' 'future versions. Please consolidate ' 'your configuration in the [cors] ' 'configuration block.') # Register with the preconstructed defaults self.oslo_conf.register_opts(subgroup_opts, section) self.add_origin(**self.oslo_conf[section]) def add_origin(self, allowed_origin, allow_credentials=True, expose_headers=None, max_age=None, allow_methods=None, allow_headers=None): '''Add another origin to this filter. :param allowed_origin: Protocol, host, and port for the allowed origin. :param allow_credentials: Whether to permit credentials. :param expose_headers: A list of headers to expose. :param max_age: Maximum cache duration. :param allow_methods: List of HTTP methods to permit. :param allow_headers: List of HTTP headers to permit from the client. :return: ''' # NOTE(dims): Support older code that still passes in # a string for allowed_origin instead of a list if isinstance(allowed_origin, str): # TODO(krotscheck): https://review.opendev.org/#/c/312687/ LOG.warning('DEPRECATED: The `allowed_origin` keyword argument in ' '`add_origin()` should be a list, found String.') allowed_origin = [allowed_origin] if allowed_origin: for origin in allowed_origin: if origin in self.allowed_origins: LOG.warning('Allowed origin [%s] already exists, skipping' % (allowed_origin,)) continue self.allowed_origins[origin] = { 'allow_credentials': allow_credentials, 'expose_headers': expose_headers, 'max_age': max_age, 'allow_methods': allow_methods, 'allow_headers': allow_headers } def process_response(self, response, request=None): '''Check for CORS headers, and decorate if necessary. Perform two checks. First, if an OPTIONS request was issued, let the application handle it, and (if necessary) decorate the response with preflight headers. In this case, if a 404 is thrown by the underlying application (i.e. if the underlying application does not handle OPTIONS requests, the response code is overridden. In the case of all other requests, regular request headers are applied. ''' # Sanity precheck: If we detect CORS headers provided by something in # in the middleware chain, assume that it knows better. if 'Access-Control-Allow-Origin' in response.headers: return response # Doublecheck for an OPTIONS request. if request.method == 'OPTIONS': return self._apply_cors_preflight_headers(request=request, response=response) # Apply regular CORS headers. self._apply_cors_request_headers(request=request, response=response) # Finally, return the response. return response @staticmethod def _split_header_values(request, header_name): """Convert a comma-separated header value into a list of values.""" values = [] if header_name in request.headers: for value in request.headers[header_name].rsplit(','): value = value.strip() if value: values.append(value) return values def _apply_cors_preflight_headers(self, request, response): """Handle CORS Preflight (Section 6.2) Given a request and a response, apply the CORS preflight headers appropriate for the request. """ # If the response contains a 2XX code, we have to assume that the # underlying middleware's response content needs to be persisted. # Otherwise, create a new response. if 200 > response.status_code or response.status_code >= 300: response = base.NoContentTypeResponse(status=webob.exc.HTTPOk.code) # Does the request have an origin header? (Section 6.2.1) if 'Origin' not in request.headers: return response # Is this origin registered? (Section 6.2.2) try: origin, cors_config = self._get_cors_config_by_origin( request.headers['Origin']) except InvalidOriginError: return response # If there's no request method, exit. (Section 6.2.3) if 'Access-Control-Request-Method' not in request.headers: LOG.debug('CORS request does not contain ' 'Access-Control-Request-Method header.') return response request_method = request.headers['Access-Control-Request-Method'] # Extract Request headers. If parsing fails, exit. (Section 6.2.4) try: request_headers = \ self._split_header_values(request, 'Access-Control-Request-Headers') except Exception: LOG.debug('Cannot parse request headers.') return response # Compare request method to permitted methods (Section 6.2.5) permitted_methods = cors_config['allow_methods'] if request_method not in permitted_methods: LOG.debug('Request method \'%s\' not in permitted list: %s' % (request_method, permitted_methods)) return response # Compare request headers to permitted headers, case-insensitively. # (Section 6.2.6) permitted_headers = [header.upper() for header in (cors_config['allow_headers'] + self.simple_headers)] for requested_header in request_headers: upper_header = requested_header.upper() if upper_header not in permitted_headers: LOG.debug('Request header \'%s\' not in permitted list: %s' % (requested_header, permitted_headers)) return response # Set the default origin permission headers. (Sections 6.2.7, 6.4) response.headers['Vary'] = 'Origin' response.headers['Access-Control-Allow-Origin'] = origin # Does this CORS configuration permit credentials? (Section 6.2.7) if cors_config['allow_credentials']: response.headers['Access-Control-Allow-Credentials'] = 'true' # Attach Access-Control-Max-Age if appropriate. (Section 6.2.8) if 'max_age' in cors_config and cors_config['max_age']: response.headers['Access-Control-Max-Age'] = \ str(cors_config['max_age']) # Attach Access-Control-Allow-Methods. (Section 6.2.9) response.headers['Access-Control-Allow-Methods'] = request_method # Attach Access-Control-Allow-Headers. (Section 6.2.10) if request_headers: response.headers['Access-Control-Allow-Headers'] = \ ','.join(request_headers) return response def _get_cors_config_by_origin(self, origin): if origin not in self.allowed_origins: if '*' in self.allowed_origins: origin = '*' else: LOG.debug('CORS request from origin \'%s\' not permitted.' % origin) raise InvalidOriginError(origin) return origin, self.allowed_origins[origin] def _apply_cors_request_headers(self, request, response): """Handle Basic CORS Request (Section 6.1) Given a request and a response, apply the CORS headers appropriate for the request to the response. """ # Does the request have an origin header? (Section 6.1.1) if 'Origin' not in request.headers: return # Is this origin registered? (Section 6.1.2) try: origin, cors_config = self._get_cors_config_by_origin( request.headers['Origin']) except InvalidOriginError: return # Set the default origin permission headers. (Sections 6.1.3 & 6.4) if 'Vary' in response.headers: response.headers['Vary'] += ',Origin' else: response.headers['Vary'] = 'Origin' response.headers['Access-Control-Allow-Origin'] = origin # Does this CORS configuration permit credentials? (Section 6.1.3) if cors_config['allow_credentials']: response.headers['Access-Control-Allow-Credentials'] = 'true' # Attach the exposed headers and exit. (Section 6.1.4) if cors_config['expose_headers']: response.headers['Access-Control-Expose-Headers'] = \ ','.join(cors_config['expose_headers'])
(application, *args, **kwargs)
70,348
oslo_middleware.cors
__init__
null
def __init__(self, application, *args, **kwargs): super(CORS, self).__init__(application, *args, **kwargs) # Begin constructing our configuration hash. self.allowed_origins = {} self._init_conf() def sanitize(csv_list): try: return [str.strip(x) for x in csv_list.split(',')] except Exception: return None
(self, application, *args, **kwargs)
70,349
oslo_middleware.cors
_apply_cors_preflight_headers
Handle CORS Preflight (Section 6.2) Given a request and a response, apply the CORS preflight headers appropriate for the request.
def _apply_cors_preflight_headers(self, request, response): """Handle CORS Preflight (Section 6.2) Given a request and a response, apply the CORS preflight headers appropriate for the request. """ # If the response contains a 2XX code, we have to assume that the # underlying middleware's response content needs to be persisted. # Otherwise, create a new response. if 200 > response.status_code or response.status_code >= 300: response = base.NoContentTypeResponse(status=webob.exc.HTTPOk.code) # Does the request have an origin header? (Section 6.2.1) if 'Origin' not in request.headers: return response # Is this origin registered? (Section 6.2.2) try: origin, cors_config = self._get_cors_config_by_origin( request.headers['Origin']) except InvalidOriginError: return response # If there's no request method, exit. (Section 6.2.3) if 'Access-Control-Request-Method' not in request.headers: LOG.debug('CORS request does not contain ' 'Access-Control-Request-Method header.') return response request_method = request.headers['Access-Control-Request-Method'] # Extract Request headers. If parsing fails, exit. (Section 6.2.4) try: request_headers = \ self._split_header_values(request, 'Access-Control-Request-Headers') except Exception: LOG.debug('Cannot parse request headers.') return response # Compare request method to permitted methods (Section 6.2.5) permitted_methods = cors_config['allow_methods'] if request_method not in permitted_methods: LOG.debug('Request method \'%s\' not in permitted list: %s' % (request_method, permitted_methods)) return response # Compare request headers to permitted headers, case-insensitively. # (Section 6.2.6) permitted_headers = [header.upper() for header in (cors_config['allow_headers'] + self.simple_headers)] for requested_header in request_headers: upper_header = requested_header.upper() if upper_header not in permitted_headers: LOG.debug('Request header \'%s\' not in permitted list: %s' % (requested_header, permitted_headers)) return response # Set the default origin permission headers. (Sections 6.2.7, 6.4) response.headers['Vary'] = 'Origin' response.headers['Access-Control-Allow-Origin'] = origin # Does this CORS configuration permit credentials? (Section 6.2.7) if cors_config['allow_credentials']: response.headers['Access-Control-Allow-Credentials'] = 'true' # Attach Access-Control-Max-Age if appropriate. (Section 6.2.8) if 'max_age' in cors_config and cors_config['max_age']: response.headers['Access-Control-Max-Age'] = \ str(cors_config['max_age']) # Attach Access-Control-Allow-Methods. (Section 6.2.9) response.headers['Access-Control-Allow-Methods'] = request_method # Attach Access-Control-Allow-Headers. (Section 6.2.10) if request_headers: response.headers['Access-Control-Allow-Headers'] = \ ','.join(request_headers) return response
(self, request, response)
70,350
oslo_middleware.cors
_apply_cors_request_headers
Handle Basic CORS Request (Section 6.1) Given a request and a response, apply the CORS headers appropriate for the request to the response.
def _apply_cors_request_headers(self, request, response): """Handle Basic CORS Request (Section 6.1) Given a request and a response, apply the CORS headers appropriate for the request to the response. """ # Does the request have an origin header? (Section 6.1.1) if 'Origin' not in request.headers: return # Is this origin registered? (Section 6.1.2) try: origin, cors_config = self._get_cors_config_by_origin( request.headers['Origin']) except InvalidOriginError: return # Set the default origin permission headers. (Sections 6.1.3 & 6.4) if 'Vary' in response.headers: response.headers['Vary'] += ',Origin' else: response.headers['Vary'] = 'Origin' response.headers['Access-Control-Allow-Origin'] = origin # Does this CORS configuration permit credentials? (Section 6.1.3) if cors_config['allow_credentials']: response.headers['Access-Control-Allow-Credentials'] = 'true' # Attach the exposed headers and exit. (Section 6.1.4) if cors_config['expose_headers']: response.headers['Access-Control-Expose-Headers'] = \ ','.join(cors_config['expose_headers'])
(self, request, response)
70,352
oslo_middleware.cors
_get_cors_config_by_origin
null
def _get_cors_config_by_origin(self, origin): if origin not in self.allowed_origins: if '*' in self.allowed_origins: origin = '*' else: LOG.debug('CORS request from origin \'%s\' not permitted.' % origin) raise InvalidOriginError(origin) return origin, self.allowed_origins[origin]
(self, origin)
70,353
oslo_middleware.cors
_init_conf
Initialize this middleware from an oslo.config instance.
def _init_conf(self): '''Initialize this middleware from an oslo.config instance.''' # First, check the configuration and register global options. self.oslo_conf.register_opts(CORS_OPTS, 'cors') allowed_origin = self._conf_get('allowed_origin', 'cors') allow_credentials = self._conf_get('allow_credentials', 'cors') expose_headers = self._conf_get('expose_headers', 'cors') max_age = self._conf_get('max_age', 'cors') allow_methods = self._conf_get('allow_methods', 'cors') allow_headers = self._conf_get('allow_headers', 'cors') # Clone our original CORS_OPTS, and set the defaults to whatever is # set in the global conf instance. This is done explicitly (instead # of **kwargs), since we don't accidentally want to catch # allowed_origin. subgroup_opts = copy.deepcopy(CORS_OPTS) cfg.set_defaults(subgroup_opts, allow_credentials=allow_credentials, expose_headers=expose_headers, max_age=max_age, allow_methods=allow_methods, allow_headers=allow_headers) # If the default configuration contains an allowed_origin, don't # forget to register that. self.add_origin(allowed_origin=allowed_origin, allow_credentials=allow_credentials, expose_headers=expose_headers, max_age=max_age, allow_methods=allow_methods, allow_headers=allow_headers) # Iterate through all the loaded config sections, looking for ones # prefixed with 'cors.' for section in self.oslo_conf.list_all_sections(): if section.startswith('cors.'): debtcollector.deprecate('Multiple configuration blocks are ' 'deprecated and will be removed in ' 'future versions. Please consolidate ' 'your configuration in the [cors] ' 'configuration block.') # Register with the preconstructed defaults self.oslo_conf.register_opts(subgroup_opts, section) self.add_origin(**self.oslo_conf[section])
(self)
70,354
oslo_middleware.cors
_split_header_values
Convert a comma-separated header value into a list of values.
@staticmethod def _split_header_values(request, header_name): """Convert a comma-separated header value into a list of values.""" values = [] if header_name in request.headers: for value in request.headers[header_name].rsplit(','): value = value.strip() if value: values.append(value) return values
(request, header_name)
70,355
oslo_middleware.cors
add_origin
Add another origin to this filter. :param allowed_origin: Protocol, host, and port for the allowed origin. :param allow_credentials: Whether to permit credentials. :param expose_headers: A list of headers to expose. :param max_age: Maximum cache duration. :param allow_methods: List of HTTP methods to permit. :param allow_headers: List of HTTP headers to permit from the client. :return:
def add_origin(self, allowed_origin, allow_credentials=True, expose_headers=None, max_age=None, allow_methods=None, allow_headers=None): '''Add another origin to this filter. :param allowed_origin: Protocol, host, and port for the allowed origin. :param allow_credentials: Whether to permit credentials. :param expose_headers: A list of headers to expose. :param max_age: Maximum cache duration. :param allow_methods: List of HTTP methods to permit. :param allow_headers: List of HTTP headers to permit from the client. :return: ''' # NOTE(dims): Support older code that still passes in # a string for allowed_origin instead of a list if isinstance(allowed_origin, str): # TODO(krotscheck): https://review.opendev.org/#/c/312687/ LOG.warning('DEPRECATED: The `allowed_origin` keyword argument in ' '`add_origin()` should be a list, found String.') allowed_origin = [allowed_origin] if allowed_origin: for origin in allowed_origin: if origin in self.allowed_origins: LOG.warning('Allowed origin [%s] already exists, skipping' % (allowed_origin,)) continue self.allowed_origins[origin] = { 'allow_credentials': allow_credentials, 'expose_headers': expose_headers, 'max_age': max_age, 'allow_methods': allow_methods, 'allow_headers': allow_headers }
(self, allowed_origin, allow_credentials=True, expose_headers=None, max_age=None, allow_methods=None, allow_headers=None)
70,357
oslo_middleware.cors
process_response
Check for CORS headers, and decorate if necessary. Perform two checks. First, if an OPTIONS request was issued, let the application handle it, and (if necessary) decorate the response with preflight headers. In this case, if a 404 is thrown by the underlying application (i.e. if the underlying application does not handle OPTIONS requests, the response code is overridden. In the case of all other requests, regular request headers are applied.
def process_response(self, response, request=None): '''Check for CORS headers, and decorate if necessary. Perform two checks. First, if an OPTIONS request was issued, let the application handle it, and (if necessary) decorate the response with preflight headers. In this case, if a 404 is thrown by the underlying application (i.e. if the underlying application does not handle OPTIONS requests, the response code is overridden. In the case of all other requests, regular request headers are applied. ''' # Sanity precheck: If we detect CORS headers provided by something in # in the middleware chain, assume that it knows better. if 'Access-Control-Allow-Origin' in response.headers: return response # Doublecheck for an OPTIONS request. if request.method == 'OPTIONS': return self._apply_cors_preflight_headers(request=request, response=response) # Apply regular CORS headers. self._apply_cors_request_headers(request=request, response=response) # Finally, return the response. return response
(self, response, request=None)
70,358
oslo_middleware.catch_errors
CatchErrors
Middleware that provides high-level error handling. It catches all exceptions from subsequent applications in WSGI pipeline to hide internal errors from API response.
class CatchErrors(base.ConfigurableMiddleware): """Middleware that provides high-level error handling. It catches all exceptions from subsequent applications in WSGI pipeline to hide internal errors from API response. """ @webob.dec.wsgify def __call__(self, req): try: response = req.get_response(self.application) except Exception: req_str = _TOKEN_RE.sub(r'\1: *****', req.as_text()) LOG.exception('An error occurred during ' 'processing the request: %s', req_str) response = webob.exc.HTTPInternalServerError() return response
(application, conf=None)
70,359
oslo_middleware.base
__init__
Base middleware constructor :param conf: a dict of options or a cfg.ConfigOpts object
def __init__(self, application, conf=None): """Base middleware constructor :param conf: a dict of options or a cfg.ConfigOpts object """ self.application = application # NOTE(sileht): If the configuration come from oslo.config # just use it. if isinstance(conf, cfg.ConfigOpts): self.conf = {} self.oslo_conf = conf else: self.conf = conf or {} if "oslo_config_project" in self.conf: if 'oslo_config_file' in self.conf: default_config_files = [self.conf['oslo_config_file']] else: default_config_files = None if 'oslo_config_program' in self.conf: program = self.conf['oslo_config_program'] else: program = None self.oslo_conf = cfg.ConfigOpts() self.oslo_conf([], project=self.conf['oslo_config_project'], prog=program, default_config_files=default_config_files, validate_default_values=True) else: # Fallback to global object self.oslo_conf = cfg.CONF
(self, application, conf=None)
70,363
oslo_middleware.correlation_id
CorrelationId
Middleware that attaches a correlation id to WSGI request
class CorrelationId(base.ConfigurableMiddleware): "Middleware that attaches a correlation id to WSGI request" def process_request(self, req): correlation_id = (req.headers.get("X_CORRELATION_ID") or uuidutils.generate_uuid()) req.headers['X_CORRELATION_ID'] = correlation_id
(application, conf=None)
70,366
oslo_middleware.correlation_id
process_request
null
def process_request(self, req): correlation_id = (req.headers.get("X_CORRELATION_ID") or uuidutils.generate_uuid()) req.headers['X_CORRELATION_ID'] = correlation_id
(self, req)
70,368
oslo_middleware.debug
Debug
Helper class that returns debug information. Can be inserted into any WSGI application chain to get information about the request and response.
class Debug(base.ConfigurableMiddleware): """Helper class that returns debug information. Can be inserted into any WSGI application chain to get information about the request and response. """ @webob.dec.wsgify def __call__(self, req): print(("*" * 40) + " REQUEST ENVIRON") for key, value in req.environ.items(): print(key, "=", value) print() resp = req.get_response(self.application) print(("*" * 40) + " RESPONSE HEADERS") for (key, value) in resp.headers.items(): print(key, "=", value) print() resp.app_iter = self.print_generator(resp.app_iter) return resp @staticmethod def print_generator(app_iter): """Prints the contents of a wrapper string iterator when iterated.""" print(("*" * 40) + " BODY") for part in app_iter: sys.stdout.write(part) sys.stdout.flush() yield part print()
(application, conf=None)
70,371
oslo_middleware.debug
print_generator
Prints the contents of a wrapper string iterator when iterated.
@staticmethod def print_generator(app_iter): """Prints the contents of a wrapper string iterator when iterated.""" print(("*" * 40) + " BODY") for part in app_iter: sys.stdout.write(part) sys.stdout.flush() yield part print()
(app_iter)
70,374
oslo_middleware.http_proxy_to_wsgi
HTTPProxyToWSGI
HTTP proxy to WSGI termination middleware. This middleware overloads WSGI environment variables with the one provided by the remote HTTP reverse proxy.
class HTTPProxyToWSGI(base.ConfigurableMiddleware): """HTTP proxy to WSGI termination middleware. This middleware overloads WSGI environment variables with the one provided by the remote HTTP reverse proxy. """ def __init__(self, application, *args, **kwargs): super(HTTPProxyToWSGI, self).__init__(application, *args, **kwargs) self.oslo_conf.register_opts(OPTS, group='oslo_middleware') @staticmethod def _parse_rfc7239_header(header): """Parses RFC7239 Forward headers. e.g. for=192.0.2.60;proto=http, for=192.0.2.60;by=203.0.113.43 """ result = [] for proxy in header.split(","): entry = {} for d in proxy.split(";"): key, _, value = d.partition("=") entry[key.lower().strip()] = value.strip() result.append(entry) return result def process_request(self, req): if not self._conf_get('enable_proxy_headers_parsing'): return fwd_hdr = req.environ.get("HTTP_FORWARDED") if fwd_hdr: proxies = self._parse_rfc7239_header(fwd_hdr) # Let's use the value from the first proxy if proxies: proxy = proxies[0] forwarded_proto = proxy.get("proto") if forwarded_proto: req.environ['wsgi.url_scheme'] = forwarded_proto forwarded_host = proxy.get("host") if forwarded_host: req.environ['HTTP_HOST'] = forwarded_host forwarded_for = proxy.get("for") if forwarded_for: req.environ['REMOTE_ADDR'] = forwarded_for else: # World before RFC7239 forwarded_proto = req.environ.get("HTTP_X_FORWARDED_PROTO") if forwarded_proto: req.environ['wsgi.url_scheme'] = forwarded_proto forwarded_host = req.environ.get("HTTP_X_FORWARDED_HOST") if forwarded_host: req.environ['HTTP_HOST'] = forwarded_host forwarded_for = req.environ.get("HTTP_X_FORWARDED_FOR") if forwarded_for: req.environ['REMOTE_ADDR'] = forwarded_for v = req.environ.get("HTTP_X_FORWARDED_PREFIX") if v: req.environ['SCRIPT_NAME'] = v + req.environ['SCRIPT_NAME']
(application, *args, **kwargs)
70,375
oslo_middleware.http_proxy_to_wsgi
__init__
null
def __init__(self, application, *args, **kwargs): super(HTTPProxyToWSGI, self).__init__(application, *args, **kwargs) self.oslo_conf.register_opts(OPTS, group='oslo_middleware')
(self, application, *args, **kwargs)
70,377
oslo_middleware.http_proxy_to_wsgi
_parse_rfc7239_header
Parses RFC7239 Forward headers. e.g. for=192.0.2.60;proto=http, for=192.0.2.60;by=203.0.113.43
@staticmethod def _parse_rfc7239_header(header): """Parses RFC7239 Forward headers. e.g. for=192.0.2.60;proto=http, for=192.0.2.60;by=203.0.113.43 """ result = [] for proxy in header.split(","): entry = {} for d in proxy.split(";"): key, _, value = d.partition("=") entry[key.lower().strip()] = value.strip() result.append(entry) return result
(header)
70,378
oslo_middleware.http_proxy_to_wsgi
process_request
null
def process_request(self, req): if not self._conf_get('enable_proxy_headers_parsing'): return fwd_hdr = req.environ.get("HTTP_FORWARDED") if fwd_hdr: proxies = self._parse_rfc7239_header(fwd_hdr) # Let's use the value from the first proxy if proxies: proxy = proxies[0] forwarded_proto = proxy.get("proto") if forwarded_proto: req.environ['wsgi.url_scheme'] = forwarded_proto forwarded_host = proxy.get("host") if forwarded_host: req.environ['HTTP_HOST'] = forwarded_host forwarded_for = proxy.get("for") if forwarded_for: req.environ['REMOTE_ADDR'] = forwarded_for else: # World before RFC7239 forwarded_proto = req.environ.get("HTTP_X_FORWARDED_PROTO") if forwarded_proto: req.environ['wsgi.url_scheme'] = forwarded_proto forwarded_host = req.environ.get("HTTP_X_FORWARDED_HOST") if forwarded_host: req.environ['HTTP_HOST'] = forwarded_host forwarded_for = req.environ.get("HTTP_X_FORWARDED_FOR") if forwarded_for: req.environ['REMOTE_ADDR'] = forwarded_for v = req.environ.get("HTTP_X_FORWARDED_PREFIX") if v: req.environ['SCRIPT_NAME'] = v + req.environ['SCRIPT_NAME']
(self, req)
70,380
oslo_middleware.healthcheck
Healthcheck
Healthcheck application used for monitoring. It will respond 200 with "OK" as the body. Or a 503 with the reason as the body if one of the backends reports an application issue. This is useful for the following reasons: * Load balancers can 'ping' this url to determine service availability. * Provides an endpoint that is similar to 'mod_status' in apache which can provide details (or no details, depending on if configured) about the activity of the server. * *(and more)* .. note:: This middleware indicates that the API is accessible but it does indicate that it is necessarily functional or that any other API request will actually work. Example requests/responses (**not** detailed mode):: $ curl -i -X HEAD "http://0.0.0.0:8775/healthcheck" HTTP/1.1 204 No Content Content-Type: text/plain; charset=UTF-8 Content-Length: 0 Date: Fri, 11 Sep 2015 18:55:08 GMT $ curl -i -X GET "http://0.0.0.0:8775/healthcheck" HTTP/1.1 200 OK Content-Type: text/plain; charset=UTF-8 Content-Length: 2 Date: Fri, 11 Sep 2015 18:55:43 GMT OK $ curl -X GET -i -H "Accept: application/json" "http://0.0.0.0:8775/healthcheck" HTTP/1.0 200 OK Date: Wed, 24 Aug 2016 06:09:58 GMT Content-Type: application/json Content-Length: 63 { "detailed": false, "reasons": [ "OK" ] } $ curl -X GET -i -H "Accept: text/html" "http://0.0.0.0:8775/healthcheck" HTTP/1.0 200 OK Date: Wed, 24 Aug 2016 06:10:42 GMT Content-Type: text/html; charset=UTF-8 Content-Length: 239 <HTML> <HEAD><TITLE>Healthcheck Status</TITLE></HEAD> <BODY> <H2>Result of 1 checks:</H2> <TABLE bgcolor="#ffffff" border="1"> <TBODY> <TR> <TH> Reason </TH> </TR> <TR> <TD>OK</TD> </TR> </TBODY> </TABLE> <HR></HR> </BODY> Example requests/responses (**detailed** mode):: $ curl -X GET -i -H "Accept: application/json" "http://0.0.0.0:8775/healthcheck" HTTP/1.0 200 OK Date: Wed, 24 Aug 2016 06:11:59 GMT Content-Type: application/json Content-Length: 3480 { "detailed": true, "gc": { "counts": [ 293, 10, 5 ], "threshold": [ 700, 10, 10 ] }, "greenthreads": [ ... ], "now": "2016-08-24 06:11:59.419267", "platform": "Linux-4.2.0-27-generic-x86_64-with-Ubuntu-14.04-trusty", "python_version": "2.7.6 (default, Jun 22 2015, 17:58:13) \n[GCC 4.8.2]", "reasons": [ { "class": "HealthcheckResult", "details": "Path '/tmp/dead' was not found", "reason": "OK" } ], "threads": [ ... ] } $ curl -X GET -i -H "Accept: text/html" "http://0.0.0.0:8775/healthcheck" HTTP/1.0 200 OK Date: Wed, 24 Aug 2016 06:36:07 GMT Content-Type: text/html; charset=UTF-8 Content-Length: 6838 <HTML> <HEAD><TITLE>Healthcheck Status</TITLE></HEAD> <BODY> <H1>Server status</H1> <B>Server hostname:</B><PRE>...</PRE> <B>Current time:</B><PRE>2016-08-24 06:36:07.302559</PRE> <B>Python version:</B><PRE>2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]</PRE> <B>Platform:</B><PRE>Linux-4.2.0-27-generic-x86_64-with-Ubuntu-14.04-trusty</PRE> <HR></HR> <H2>Garbage collector:</H2> <B>Counts:</B><PRE>(77, 1, 6)</PRE> <B>Thresholds:</B><PRE>(700, 10, 10)</PRE> <HR></HR> <H2>Result of 1 checks:</H2> <TABLE bgcolor="#ffffff" border="1"> <TBODY> <TR> <TH> Kind </TH> <TH> Reason </TH> <TH> Details </TH> </TR> <TR> <TD>HealthcheckResult</TD> <TD>OK</TD> <TD>Path &#39;/tmp/dead&#39; was not found</TD> </TR> </TBODY> </TABLE> <HR></HR> <H2>1 greenthread(s) active:</H2> <TABLE bgcolor="#ffffff" border="1"> <TBODY> <TR> <TD><PRE> File &#34;oslo_middleware/healthcheck/__main__.py&#34;, line 94, in &lt;module&gt; main() File &#34;oslo_middleware/healthcheck/__main__.py&#34;, line 90, in main server.serve_forever() ... </PRE></TD> </TR> </TBODY> </TABLE> <HR></HR> <H2>1 thread(s) active:</H2> <TABLE bgcolor="#ffffff" border="1"> <TBODY> <TR> <TD><PRE> File &#34;oslo_middleware/healthcheck/__main__.py&#34;, line 94, in &lt;module&gt; main() File &#34;oslo_middleware/healthcheck/__main__.py&#34;, line 90, in main server.serve_forever() .... </TR> </TBODY> </TABLE> </BODY> </HTML> Example of paste configuration: .. code-block:: ini [app:healthcheck] use = egg:oslo.middleware:healthcheck backends = disable_by_file disable_by_file_path = /var/run/nova/healthcheck_disable [pipeline:public_api] pipeline = healthcheck sizelimit [...] public_service Multiple filter sections can be defined if it desired to have pipelines with different healthcheck configuration, example: .. code-block:: ini [composite:public_api] use = egg:Paste#urlmap / = public_api_pipeline /healthcheck = healthcheck_public [composite:admin_api] use = egg:Paste#urlmap / = admin_api_pipeline /healthcheck = healthcheck_admin [pipeline:public_api_pipeline] pipeline = sizelimit [...] public_service [pipeline:admin_api_pipeline] pipeline = sizelimit [...] admin_service [app:healthcheck_public] use = egg:oslo.middleware:healthcheck backends = disable_by_file disable_by_file_path = /var/run/nova/healthcheck_public_disable [filter:healthcheck_admin] use = egg:oslo.middleware:healthcheck backends = disable_by_file disable_by_file_path = /var/run/nova/healthcheck_admin_disable
class Healthcheck(base.ConfigurableMiddleware): """Healthcheck application used for monitoring. It will respond 200 with "OK" as the body. Or a 503 with the reason as the body if one of the backends reports an application issue. This is useful for the following reasons: * Load balancers can 'ping' this url to determine service availability. * Provides an endpoint that is similar to 'mod_status' in apache which can provide details (or no details, depending on if configured) about the activity of the server. * *(and more)* .. note:: This middleware indicates that the API is accessible but it does indicate that it is necessarily functional or that any other API request will actually work. Example requests/responses (**not** detailed mode):: $ curl -i -X HEAD "http://0.0.0.0:8775/healthcheck" HTTP/1.1 204 No Content Content-Type: text/plain; charset=UTF-8 Content-Length: 0 Date: Fri, 11 Sep 2015 18:55:08 GMT $ curl -i -X GET "http://0.0.0.0:8775/healthcheck" HTTP/1.1 200 OK Content-Type: text/plain; charset=UTF-8 Content-Length: 2 Date: Fri, 11 Sep 2015 18:55:43 GMT OK $ curl -X GET -i -H "Accept: application/json" "http://0.0.0.0:8775/healthcheck" HTTP/1.0 200 OK Date: Wed, 24 Aug 2016 06:09:58 GMT Content-Type: application/json Content-Length: 63 { "detailed": false, "reasons": [ "OK" ] } $ curl -X GET -i -H "Accept: text/html" "http://0.0.0.0:8775/healthcheck" HTTP/1.0 200 OK Date: Wed, 24 Aug 2016 06:10:42 GMT Content-Type: text/html; charset=UTF-8 Content-Length: 239 <HTML> <HEAD><TITLE>Healthcheck Status</TITLE></HEAD> <BODY> <H2>Result of 1 checks:</H2> <TABLE bgcolor="#ffffff" border="1"> <TBODY> <TR> <TH> Reason </TH> </TR> <TR> <TD>OK</TD> </TR> </TBODY> </TABLE> <HR></HR> </BODY> Example requests/responses (**detailed** mode):: $ curl -X GET -i -H "Accept: application/json" "http://0.0.0.0:8775/healthcheck" HTTP/1.0 200 OK Date: Wed, 24 Aug 2016 06:11:59 GMT Content-Type: application/json Content-Length: 3480 { "detailed": true, "gc": { "counts": [ 293, 10, 5 ], "threshold": [ 700, 10, 10 ] }, "greenthreads": [ ... ], "now": "2016-08-24 06:11:59.419267", "platform": "Linux-4.2.0-27-generic-x86_64-with-Ubuntu-14.04-trusty", "python_version": "2.7.6 (default, Jun 22 2015, 17:58:13) \\n[GCC 4.8.2]", "reasons": [ { "class": "HealthcheckResult", "details": "Path '/tmp/dead' was not found", "reason": "OK" } ], "threads": [ ... ] } $ curl -X GET -i -H "Accept: text/html" "http://0.0.0.0:8775/healthcheck" HTTP/1.0 200 OK Date: Wed, 24 Aug 2016 06:36:07 GMT Content-Type: text/html; charset=UTF-8 Content-Length: 6838 <HTML> <HEAD><TITLE>Healthcheck Status</TITLE></HEAD> <BODY> <H1>Server status</H1> <B>Server hostname:</B><PRE>...</PRE> <B>Current time:</B><PRE>2016-08-24 06:36:07.302559</PRE> <B>Python version:</B><PRE>2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]</PRE> <B>Platform:</B><PRE>Linux-4.2.0-27-generic-x86_64-with-Ubuntu-14.04-trusty</PRE> <HR></HR> <H2>Garbage collector:</H2> <B>Counts:</B><PRE>(77, 1, 6)</PRE> <B>Thresholds:</B><PRE>(700, 10, 10)</PRE> <HR></HR> <H2>Result of 1 checks:</H2> <TABLE bgcolor="#ffffff" border="1"> <TBODY> <TR> <TH> Kind </TH> <TH> Reason </TH> <TH> Details </TH> </TR> <TR> <TD>HealthcheckResult</TD> <TD>OK</TD> <TD>Path &#39;/tmp/dead&#39; was not found</TD> </TR> </TBODY> </TABLE> <HR></HR> <H2>1 greenthread(s) active:</H2> <TABLE bgcolor="#ffffff" border="1"> <TBODY> <TR> <TD><PRE> File &#34;oslo_middleware/healthcheck/__main__.py&#34;, line 94, in &lt;module&gt; main() File &#34;oslo_middleware/healthcheck/__main__.py&#34;, line 90, in main server.serve_forever() ... </PRE></TD> </TR> </TBODY> </TABLE> <HR></HR> <H2>1 thread(s) active:</H2> <TABLE bgcolor="#ffffff" border="1"> <TBODY> <TR> <TD><PRE> File &#34;oslo_middleware/healthcheck/__main__.py&#34;, line 94, in &lt;module&gt; main() File &#34;oslo_middleware/healthcheck/__main__.py&#34;, line 90, in main server.serve_forever() .... </TR> </TBODY> </TABLE> </BODY> </HTML> Example of paste configuration: .. code-block:: ini [app:healthcheck] use = egg:oslo.middleware:healthcheck backends = disable_by_file disable_by_file_path = /var/run/nova/healthcheck_disable [pipeline:public_api] pipeline = healthcheck sizelimit [...] public_service Multiple filter sections can be defined if it desired to have pipelines with different healthcheck configuration, example: .. code-block:: ini [composite:public_api] use = egg:Paste#urlmap / = public_api_pipeline /healthcheck = healthcheck_public [composite:admin_api] use = egg:Paste#urlmap / = admin_api_pipeline /healthcheck = healthcheck_admin [pipeline:public_api_pipeline] pipeline = sizelimit [...] public_service [pipeline:admin_api_pipeline] pipeline = sizelimit [...] admin_service [app:healthcheck_public] use = egg:oslo.middleware:healthcheck backends = disable_by_file disable_by_file_path = /var/run/nova/healthcheck_public_disable [filter:healthcheck_admin] use = egg:oslo.middleware:healthcheck backends = disable_by_file disable_by_file_path = /var/run/nova/healthcheck_admin_disable """ NAMESPACE = "oslo.middleware.healthcheck" HEALTHY_TO_STATUS_CODES = { True: webob.exc.HTTPOk.code, False: webob.exc.HTTPServiceUnavailable.code, } HEAD_HEALTHY_TO_STATUS_CODES = { True: webob.exc.HTTPNoContent.code, False: webob.exc.HTTPServiceUnavailable.code, } PLAIN_RESPONSE_TEMPLATE = """ {% for reason in reasons %} {% if reason %}{{reason}}{% endif -%} {% endfor %} """ HTML_RESPONSE_TEMPLATE = """ <HTML> <HEAD><TITLE>Healthcheck Status</TITLE></HEAD> <BODY> {% if detailed -%} <H1>Server status</H1> {% if hostname -%} <B>Server hostname:</B><PRE>{{hostname|e}}</PRE> {%- endif %} <B>Current time:</B><PRE>{{now|e}}</PRE> <B>Python version:</B><PRE>{{python_version|e}}</PRE> <B>Platform:</B><PRE>{{platform|e}}</PRE> <HR></HR> <H2>Garbage collector:</H2> <B>Counts:</B><PRE>{{gc.counts|e}}</PRE> <B>Thresholds:</B><PRE>{{gc.threshold|e}}</PRE> <HR></HR> {%- endif %} <H2>Result of {{results|length}} checks:</H2> <TABLE bgcolor="#ffffff" border="1"> <TBODY> <TR> {% if detailed -%} <TH> Kind </TH> <TH> Reason </TH> <TH> Details </TH> {% else %} <TH> Reason </TH> {%- endif %} </TR> {% for result in results -%} {% if result.reason -%} <TR> {% if detailed -%} <TD>{{result.class|e}}</TD> {%- endif %} <TD>{{result.reason|e}}</TD> {% if detailed -%} <TD>{{result.details|e}}</TD> {%- endif %} </TR> {%- endif %} {%- endfor %} </TBODY> </TABLE> <HR></HR> {% if detailed -%} {% if greenthreads -%} <H2>{{greenthreads|length}} greenthread(s) active:</H2> <TABLE bgcolor="#ffffff" border="1"> <TBODY> {% for stack in greenthreads -%} <TR> <TD><PRE>{{stack|e}}</PRE></TD> </TR> {%- endfor %} </TBODY> </TABLE> <HR></HR> {%- endif %} {% if threads -%} <H2>{{threads|length}} thread(s) active:</H2> <TABLE bgcolor="#ffffff" border="1"> <TBODY> {% for stack in threads -%} <TR> <TD><PRE>{{stack|e}}</PRE></TD> </TR> {%- endfor %} </TBODY> </TABLE> {%- endif %} {%- endif %} </BODY> </HTML> """ def __init__(self, *args, **kwargs): super(Healthcheck, self).__init__(*args, **kwargs) self.oslo_conf.register_opts(opts.HEALTHCHECK_OPTS, group='healthcheck') self._path = self._conf_get('path') self._show_details = self._conf_get('detailed') self._source_ranges = [ ipaddress.ip_network(r) for r in self._conf_get('allowed_source_ranges')] self._ignore_proxied_requests = self._conf_get( 'ignore_proxied_requests') self._backends = stevedore.NamedExtensionManager( self.NAMESPACE, self._conf_get('backends'), name_order=True, invoke_on_load=True, invoke_args=(self.oslo_conf, self.conf)) self._accept_to_functor = collections.OrderedDict([ # Order here matters... ('text/plain', self._make_text_response), ('text/html', self._make_html_response), ('application/json', self._make_json_response), ]) self._accept_order = tuple(self._accept_to_functor) # When no accept type matches instead of returning 406 we will # always return text/plain (because sending an error from this # middleware actually can cause issues). self._default_accept = 'text/plain' self._ignore_path = False def _conf_get(self, key, group='healthcheck'): return super(Healthcheck, self)._conf_get(key, group=group) @removals.remove( message="The healthcheck middleware must now be configured as " "an application, not as a filter") @classmethod def factory(cls, global_conf, **local_conf): return super(Healthcheck, cls).factory(global_conf, **local_conf) @classmethod def app_factory(cls, global_conf, **local_conf): """Factory method for paste.deploy. :param global_conf: dict of options for all middlewares (usually the [DEFAULT] section of the paste deploy configuration file) :param local_conf: options dedicated to this middleware (usually the option defined in the middleware section of the paste deploy configuration file) """ conf = global_conf.copy() if global_conf else {} conf.update(local_conf) o = cls(application=None, conf=conf) o._ignore_path = True return o @staticmethod def _get_threadstacks(): threadstacks = [] try: active_frames = sys._current_frames() except AttributeError: pass else: buf = io.StringIO() for stack in active_frames.values(): traceback.print_stack(stack, file=buf) threadstacks.append(buf.getvalue()) buf.seek(0) buf.truncate() return threadstacks @staticmethod def _get_greenstacks(): greenstacks = [] if greenlet is not None: buf = io.StringIO() for gt in _find_objects(greenlet.greenlet): traceback.print_stack(gt.gr_frame, file=buf) greenstacks.append(buf.getvalue()) buf.seek(0) buf.truncate() return greenstacks @staticmethod def _pretty_json_dumps(contents): return json.dumps(contents, indent=4, sort_keys=True) @staticmethod def _are_results_healthy(results): for result in results: if not result.available: return False return True def _make_text_response(self, results, healthy): params = { 'reasons': [result.reason for result in results], 'detailed': self._show_details, } body = _expand_template(self.PLAIN_RESPONSE_TEMPLATE, params) return (body.strip(), 'text/plain') def _make_json_response(self, results, healthy): if self._show_details: body = { 'detailed': True, 'python_version': sys.version, 'now': str(timeutils.utcnow()), 'platform': platform.platform(), 'gc': { 'counts': gc.get_count(), 'threshold': gc.get_threshold(), }, } reasons = [] for result in results: reasons.append({ 'reason': result.reason, 'details': result.details or '', 'class': reflection.get_class_name(result, fully_qualified=False), }) body['reasons'] = reasons body['greenthreads'] = self._get_greenstacks() body['threads'] = self._get_threadstacks() else: body = { 'reasons': [result.reason for result in results], 'detailed': False, } return (self._pretty_json_dumps(body), 'application/json') def _make_head_response(self, results, healthy): return ( "", "text/plain") def _make_html_response(self, results, healthy): try: hostname = socket.gethostname() except socket.error: hostname = None translated_results = [] for result in results: translated_results.append({ 'details': result.details or '', 'reason': result.reason, 'class': reflection.get_class_name(result, fully_qualified=False), }) params = { 'healthy': healthy, 'hostname': hostname, 'results': translated_results, 'detailed': self._show_details, 'now': str(timeutils.utcnow()), 'python_version': sys.version, 'platform': platform.platform(), 'gc': { 'counts': gc.get_count(), 'threshold': gc.get_threshold(), }, 'threads': self._get_threadstacks(), 'greenthreads': self._get_threadstacks(), } body = _expand_template(self.HTML_RESPONSE_TEMPLATE, params) return (body.strip(), 'text/html') @webob.dec.wsgify def process_request(self, req): if not self._ignore_path and req.path != self._path: return None if self._source_ranges: remote_addr = ipaddress.ip_address(req.remote_addr) for r in self._source_ranges: if r.version == remote_addr.version and remote_addr in r: break else: # Because source ip is not included in allowed ranges, ignore # the request in this middleware. return None if self._ignore_proxied_requests: for hdr in [ 'FORWARDED', 'FORWARDED_PROTO', 'FORWARDED_HOST', 'FORWARDED_FOR', 'FORWARDED_PREFIX']: if req.environ.get("HTTP_X_%s" % hdr): return None results = [ext.obj.healthcheck(req.server_port) for ext in self._backends] healthy = self._are_results_healthy(results) if req.method == "HEAD": functor = self._make_head_response status = self.HEAD_HEALTHY_TO_STATUS_CODES[healthy] else: status = self.HEALTHY_TO_STATUS_CODES[healthy] try: offers = req.accept.acceptable_offers(self._accept_order) accept_type = offers[0][0] except IndexError: accept_type = self._default_accept functor = self._accept_to_functor[accept_type] body, content_type = functor(results, healthy) return webob.response.Response(status=status, body=body, charset='UTF-8', content_type=content_type)
(*args, **kwargs)
70,381
oslo_middleware.healthcheck
__init__
null
def __init__(self, *args, **kwargs): super(Healthcheck, self).__init__(*args, **kwargs) self.oslo_conf.register_opts(opts.HEALTHCHECK_OPTS, group='healthcheck') self._path = self._conf_get('path') self._show_details = self._conf_get('detailed') self._source_ranges = [ ipaddress.ip_network(r) for r in self._conf_get('allowed_source_ranges')] self._ignore_proxied_requests = self._conf_get( 'ignore_proxied_requests') self._backends = stevedore.NamedExtensionManager( self.NAMESPACE, self._conf_get('backends'), name_order=True, invoke_on_load=True, invoke_args=(self.oslo_conf, self.conf)) self._accept_to_functor = collections.OrderedDict([ # Order here matters... ('text/plain', self._make_text_response), ('text/html', self._make_html_response), ('application/json', self._make_json_response), ]) self._accept_order = tuple(self._accept_to_functor) # When no accept type matches instead of returning 406 we will # always return text/plain (because sending an error from this # middleware actually can cause issues). self._default_accept = 'text/plain' self._ignore_path = False
(self, *args, **kwargs)
70,382
oslo_middleware.healthcheck
_are_results_healthy
null
@staticmethod def _are_results_healthy(results): for result in results: if not result.available: return False return True
(results)
70,383
oslo_middleware.healthcheck
_conf_get
null
def _conf_get(self, key, group='healthcheck'): return super(Healthcheck, self)._conf_get(key, group=group)
(self, key, group='healthcheck')
70,384
oslo_middleware.healthcheck
_get_greenstacks
null
@staticmethod def _get_greenstacks(): greenstacks = [] if greenlet is not None: buf = io.StringIO() for gt in _find_objects(greenlet.greenlet): traceback.print_stack(gt.gr_frame, file=buf) greenstacks.append(buf.getvalue()) buf.seek(0) buf.truncate() return greenstacks
()
70,385
oslo_middleware.healthcheck
_get_threadstacks
null
@staticmethod def _get_threadstacks(): threadstacks = [] try: active_frames = sys._current_frames() except AttributeError: pass else: buf = io.StringIO() for stack in active_frames.values(): traceback.print_stack(stack, file=buf) threadstacks.append(buf.getvalue()) buf.seek(0) buf.truncate() return threadstacks
()
70,386
oslo_middleware.healthcheck
_make_head_response
null
def _make_head_response(self, results, healthy): return ( "", "text/plain")
(self, results, healthy)
70,387
oslo_middleware.healthcheck
_make_html_response
null
def _make_html_response(self, results, healthy): try: hostname = socket.gethostname() except socket.error: hostname = None translated_results = [] for result in results: translated_results.append({ 'details': result.details or '', 'reason': result.reason, 'class': reflection.get_class_name(result, fully_qualified=False), }) params = { 'healthy': healthy, 'hostname': hostname, 'results': translated_results, 'detailed': self._show_details, 'now': str(timeutils.utcnow()), 'python_version': sys.version, 'platform': platform.platform(), 'gc': { 'counts': gc.get_count(), 'threshold': gc.get_threshold(), }, 'threads': self._get_threadstacks(), 'greenthreads': self._get_threadstacks(), } body = _expand_template(self.HTML_RESPONSE_TEMPLATE, params) return (body.strip(), 'text/html')
(self, results, healthy)
70,388
oslo_middleware.healthcheck
_make_json_response
null
def _make_json_response(self, results, healthy): if self._show_details: body = { 'detailed': True, 'python_version': sys.version, 'now': str(timeutils.utcnow()), 'platform': platform.platform(), 'gc': { 'counts': gc.get_count(), 'threshold': gc.get_threshold(), }, } reasons = [] for result in results: reasons.append({ 'reason': result.reason, 'details': result.details or '', 'class': reflection.get_class_name(result, fully_qualified=False), }) body['reasons'] = reasons body['greenthreads'] = self._get_greenstacks() body['threads'] = self._get_threadstacks() else: body = { 'reasons': [result.reason for result in results], 'detailed': False, } return (self._pretty_json_dumps(body), 'application/json')
(self, results, healthy)
70,389
oslo_middleware.healthcheck
_make_text_response
null
def _make_text_response(self, results, healthy): params = { 'reasons': [result.reason for result in results], 'detailed': self._show_details, } body = _expand_template(self.PLAIN_RESPONSE_TEMPLATE, params) return (body.strip(), 'text/plain')
(self, results, healthy)
70,390
oslo_middleware.healthcheck
_pretty_json_dumps
null
@staticmethod def _pretty_json_dumps(contents): return json.dumps(contents, indent=4, sort_keys=True)
(contents)
70,392
oslo_middleware.sizelimit
RequestBodySizeLimiter
Limit the size of incoming requests.
class RequestBodySizeLimiter(base.ConfigurableMiddleware): """Limit the size of incoming requests.""" def __init__(self, application, conf=None): super(RequestBodySizeLimiter, self).__init__(application, conf) self.oslo_conf.register_opts(_opts, group='oslo_middleware') @webob.dec.wsgify def __call__(self, req): max_size = self._conf_get('max_request_body_size') if (req.content_length is not None and req.content_length > max_size): msg = _("Request is too large. " "Larger than max_request_body_size (%s).") % max_size LOG.info(msg) raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg) if req.content_length is None: limiter = LimitingReader(req.body_file, max_size) req.body_file = limiter return self.application
(application, conf=None)
70,393
oslo_middleware.sizelimit
__init__
null
def __init__(self, application, conf=None): super(RequestBodySizeLimiter, self).__init__(application, conf) self.oslo_conf.register_opts(_opts, group='oslo_middleware')
(self, application, conf=None)
70,397
oslo_middleware.request_id
RequestId
Middleware that ensures request ID. It ensures to assign request ID for each API request and set it to request environment. The request ID is also added to API response.
class RequestId(base.ConfigurableMiddleware): """Middleware that ensures request ID. It ensures to assign request ID for each API request and set it to request environment. The request ID is also added to API response. """ # if compat_headers is set, we also return the request_id in those # headers as well. This allows projects like Nova to adopt # oslo.middleware without impacting existing users. compat_headers = [] def set_global_req_id(self, req): gr_id = req.headers.get(INBOUND_HEADER, "") if re.match(ID_FORMAT, gr_id): req.environ[GLOBAL_REQ_ID] = gr_id # TODO(sdague): it would be nice to warn if we dropped a bogus # request_id, but the infrastructure for doing that isn't yet # setup at this stage. @webob.dec.wsgify def __call__(self, req): self.set_global_req_id(req) req_id = context.generate_request_id() req.environ[ENV_REQUEST_ID] = req_id response = req.get_response(self.application) return_headers = [HTTP_RESP_HEADER_REQUEST_ID] return_headers.extend(self.compat_headers) for header in return_headers: if header not in response.headers: response.headers.add(header, req_id) return response
(application, conf=None)
70,402
oslo_middleware.request_id
set_global_req_id
null
def set_global_req_id(self, req): gr_id = req.headers.get(INBOUND_HEADER, "") if re.match(ID_FORMAT, gr_id): req.environ[GLOBAL_REQ_ID] = gr_id # TODO(sdague): it would be nice to warn if we dropped a bogus # request_id, but the infrastructure for doing that isn't yet # setup at this stage.
(self, req)
70,416
netoapi.errors
DependencyNotFoundError
Custom exception for missing dependency
class DependencyNotFoundError(Exception): """Custom exception for missing dependency"""
null
70,417
netoapi.api_client
NetoAPIClient
The api client class provides a persistent HTTP session and the functionality to execute api requests
class NetoAPIClient: """The api client class provides a persistent HTTP session and the functionality to execute api requests""" def __init__(self, endpoint: str, username: str, key: str) -> None: self.endpoint = endpoint self._session = get_api_session() self._session.auth_session(username, key) self._connection_timeout = 5 self._response_timeout = 5 @property def timeout(self) -> tuple: """Sets the values in seconds for connection & request timeouts respectively. Set each value with a tuple(int, int) or set both to the same value with an integer. Set either or both to None if you want to disable that timeout and wait forever.""" return (self._connection_timeout, self._response_timeout) @timeout.setter def timeout(self, val: int | None | tuple[int | None, int | None]): if not val or type(val) == int: self._connection_timeout = val self._response_timeout = val elif type(val) == tuple: self._connection_timeout = val[0] self._response_timeout = val[1] else: raise TypeError( f"timeout value must be int or tuple(int,int) or None not {type(val).__name__}" ) def execute_api_call(self, action: str, payload: dict) -> dict: """Execute an api call and return the JSON response""" try: response = self._session.send_request( url=self.endpoint, headers={"NETOAPI_ACTION": action}, json=payload, timeout=(self.timeout), ) response.raise_for_status() api_response: dict = response.json() except Exception as e: raise NetoAPIRequestError( f"An error occured during the request: {e}" ) from None return api_response
(endpoint: str, username: str, key: str) -> None
70,418
netoapi.api_client
__init__
null
def __init__(self, endpoint: str, username: str, key: str) -> None: self.endpoint = endpoint self._session = get_api_session() self._session.auth_session(username, key) self._connection_timeout = 5 self._response_timeout = 5
(self, endpoint: str, username: str, key: str) -> NoneType
70,419
netoapi.api_client
execute_api_call
Execute an api call and return the JSON response
def execute_api_call(self, action: str, payload: dict) -> dict: """Execute an api call and return the JSON response""" try: response = self._session.send_request( url=self.endpoint, headers={"NETOAPI_ACTION": action}, json=payload, timeout=(self.timeout), ) response.raise_for_status() api_response: dict = response.json() except Exception as e: raise NetoAPIRequestError( f"An error occured during the request: {e}" ) from None return api_response
(self, action: str, payload: dict) -> dict
70,420
netoapi.errors
NetoAPIRequestError
Custom exception for request errors raised by the NetoAPIClient
class NetoAPIRequestError(Exception): """Custom exception for request errors raised by the NetoAPIClient"""
null
70,428
pybrightness.controller
custom
Set brightness to a custom level. - | Since package uses in-built apple script (for macOS), the only way to achieve this is to set the | brightness to absolute minimum/maximum and increase/decrease the required % from there. Args: percent: Percentage of brightness to be set. logger: Bring your own logger.
def custom(percent: int, logger: logging.Logger = None) -> None: """Set brightness to a custom level. - | Since package uses in-built apple script (for macOS), the only way to achieve this is to set the | brightness to absolute minimum/maximum and increase/decrease the required % from there. Args: percent: Percentage of brightness to be set. logger: Bring your own logger. """ settings.logger = logger assert isinstance(percent, int) and 0 <= percent <= 100, "value should be an integer between 0 and 100" if settings.operating_system == "Darwin": decrease() for _ in range(round((16 * int(percent)) / 100)): _run(commands.MAC_INCREASE) elif settings.operating_system == "Windows": _run(["powershell", commands.WINDOWS.format(l=percent)]) elif settings.operating_system == "Linux": eval_linux() _run(f"echo {settings.root_password} | sudo -S brightnessctl s {percent} > /dev/null") else: raise OS_ERROR
(percent: int, logger: Optional[logging.Logger] = None) -> NoneType
70,429
pybrightness.controller
decrease
Decreases the brightness to minimum.
def decrease(logger: logging.Logger = None) -> None: """Decreases the brightness to minimum.""" settings.logger = logger if settings.operating_system == "Darwin": for _ in range(16): _run(commands.MAC_DECREASE) elif settings.operating_system == "Windows": _run(["powershell", commands.WINDOWS.format(l=0)]) elif settings.operating_system == "Linux": eval_linux() _run(f"echo {settings.root_password} | sudo -S brightnessctl s 0 > /dev/null") else: raise OS_ERROR
(logger: Optional[logging.Logger] = None) -> NoneType
70,430
pybrightness.controller
increase
Increases the brightness to maximum.
def increase(logger: logging.Logger = None) -> None: """Increases the brightness to maximum.""" settings.logger = logger if settings.operating_system == "Darwin": for _ in range(16): _run(commands.MAC_INCREASE) elif settings.operating_system == "Windows": _run(["powershell", commands.WINDOWS.format(l=100)]) elif settings.operating_system == "Linux": eval_linux() _run(f"echo {settings.root_password} | sudo -S brightnessctl s 100 > /dev/null") else: raise OS_ERROR
(logger: Optional[logging.Logger] = None) -> NoneType
70,575
pdoc
pdoc
Render the documentation for a list of modules. - If `output_directory` is `None`, returns the rendered documentation for the first module in the list. - If `output_directory` is set, recursively writes the rendered output for all specified modules and their submodules to the target destination. Rendering options can be configured by calling `pdoc.render.configure` in advance.
def pdoc( *modules: Path | str, output_directory: Path | None = None, ) -> str | None: """ Render the documentation for a list of modules. - If `output_directory` is `None`, returns the rendered documentation for the first module in the list. - If `output_directory` is set, recursively writes the rendered output for all specified modules and their submodules to the target destination. Rendering options can be configured by calling `pdoc.render.configure` in advance. """ all_modules: dict[str, doc.Module] = {} for module_name in extract.walk_specs(modules): all_modules[module_name] = doc.Module.from_name(module_name) for module in all_modules.values(): out = render.html_module(module, all_modules) if not output_directory: return out else: outfile = output_directory / f"{module.fullname.replace('.', '/')}.html" outfile.parent.mkdir(parents=True, exist_ok=True) outfile.write_bytes(out.encode()) assert output_directory index = render.html_index(all_modules) if index: (output_directory / "index.html").write_bytes(index.encode()) search = render.search_index(all_modules) if search: (output_directory / "search.js").write_bytes(search.encode()) return None
(*modules: pathlib.Path | str, output_directory: Optional[pathlib.Path] = None) -> str | None