code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
from subprocess import Popen, PIPE # Wait until ready t0 = time.time() # Wait no more than these many seconds time_out = 30 running = True while running and time.time() - t0 < time_out: if os.name == 'nt': p = Popen( 'tasklist | find "%s"' % arg1, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=False) else: p = Popen( 'ps aux | grep %s' % arg1, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) lines = p.stdout.readlines() running = False for line in lines: # this kills all java.exe and python including self in windows if ('%s' % arg2 in line) or (os.name == 'nt' and '%s' % arg1 in line): running = True # Get pid fields = line.strip().split() info('Stopping %s (process number %s)' % (arg1, fields[1])) if os.name == 'nt': kill = 'taskkill /F /PID "%s"' % fields[1] else: kill = 'kill -9 %s 2> /dev/null' % fields[1] os.system(kill) # Give it a little more time time.sleep(1) else: pass if running: raise Exception('Could not stop %s: ' 'Running processes are\n%s' % (arg1, '\n'.join( [l.strip() for l in lines])))
def kill(arg1, arg2)
Stops a proces that contains arg1 and is filtered by arg2
2.935536
2.920348
1.005201
original_bulma_dir = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'static', 'bulma' ) shutil.copytree(original_bulma_dir, self.static_root_bulma_dir)
def copy_bulma_files(self)
Copies Bulma static files from package's static/bulma into project's STATIC_ROOT/bulma
2.568582
2.265943
1.13356
async def wrapped(request, **kwargs): session = await get_session(request) if 'token' not in session: return web.HTTPFound(cfg.oauth_redirect_path) client = GoogleClient( client_id=cfg.client_id, client_secret=cfg.client_secret, access_token=session['token'] ) try: user, info = await client.user_info() except Exception: return web.HTTPFound(cfg.oauth_redirect_path) return await fn(request, user, **kwargs) return wrapped
def login_required(fn)
auth decorator call function(request, user: <aioauth_client User object>)
2.722472
2.705913
1.006119
# build the url the same way aiohttp will build the query later on # cf https://github.com/KeepSafe/aiohttp/blob/master/aiohttp/client.py#L151 # and https://github.com/KeepSafe/aiohttp/blob/master/aiohttp/client_reqrep.py#L81 url = yarl.URL(url).with_query(sorted(params.items())) url, params = str(url).split('?', 1) method = method.upper() signature = b"&".join(map(self._escape, (method, url, params))) key = self._escape(consumer_secret) + b"&" if oauth_token_secret: key += self._escape(oauth_token_secret) hashed = hmac.new(key, signature, sha1) return base64.b64encode(hashed.digest()).decode()
def sign(self, consumer_secret, method, url, oauth_token_secret=None, **params)
Create a signature using HMAC-SHA1.
3.224849
3.15736
1.021375
key = self._escape(consumer_secret) + b'&' if oauth_token_secret: key += self._escape(oauth_token_secret) return key.decode()
def sign(self, consumer_secret, method, url, oauth_token_secret=None, **params)
Create a signature using PLAINTEXT.
4.678065
4.049242
1.155294
if self.base_url and not url.startswith(('http://', 'https://')): return urljoin(self.base_url, url) return url
def _get_url(self, url)
Build provider's url. Join with base_url part if needed.
2.92539
2.21687
1.319604
session = self.session or aiohttp.ClientSession( loop=loop, conn_timeout=timeout, read_timeout=timeout) try: async with session.request(method, url, **kwargs) as response: if response.status / 100 > 2: raise web.HTTPBadRequest( reason='HTTP status code: %s' % response.status) if 'json' in response.headers.get('CONTENT-TYPE'): data = await response.json() else: data = await response.text() data = dict(parse_qsl(data)) return data except asyncio.TimeoutError: raise web.HTTPBadRequest(reason='HTTP Timeout') finally: if not self.session and not session.closed: await session.close()
async def _request(self, method, url, loop=None, timeout=None, **kwargs)
Make a request through AIOHTTP.
2.437051
2.36061
1.032382
if not self.user_info_url: raise NotImplementedError( 'The provider doesnt support user_info method.') data = await self.request('GET', self.user_info_url, loop=loop, **kwargs) user = User(**dict(self.user_parse(data))) return user, data
async def user_info(self, loop=None, **kwargs)
Load user information from provider.
4.70673
3.933121
1.196691
oparams = { 'oauth_consumer_key': self.consumer_key, 'oauth_nonce': sha1(str(RANDOM()).encode('ascii')).hexdigest(), 'oauth_signature_method': self.signature.name, 'oauth_timestamp': str(int(time.time())), 'oauth_version': self.version, } oparams.update(params or {}) if self.oauth_token: oparams['oauth_token'] = self.oauth_token url = self._get_url(url) if urlsplit(url).query: raise ValueError( 'Request parameters should be in the "params" parameter, ' 'not inlined in the URL') oparams['oauth_signature'] = self.signature.sign( self.consumer_secret, method, url, oauth_token_secret=self.oauth_token_secret, **oparams) self.logger.debug("%s %s", url, oparams) return self._request(method, url, params=oparams, **aio_kwargs)
def request(self, method, url, params=None, **aio_kwargs)
Make a request to provider.
2.678699
2.59407
1.032624
params = dict(self.params, **params) data = await self.request('GET', self.request_token_url, params=params, loop=loop) self.oauth_token = data.get('oauth_token') self.oauth_token_secret = data.get('oauth_token_secret') return self.oauth_token, self.oauth_token_secret, data
async def get_request_token(self, loop=None, **params)
Get a request_token and request_token_secret from OAuth1 provider.
2.104568
1.936076
1.087027
# Possibility to provide REQUEST DATA to the method if not isinstance(oauth_verifier, str) and self.shared_key in oauth_verifier: oauth_verifier = oauth_verifier[self.shared_key] if request_token and self.oauth_token != request_token: raise web.HTTPBadRequest( reason='Failed to obtain OAuth 1.0 access token. ' 'Request token is invalid') data = await self.request('POST', self.access_token_url, params={ 'oauth_verifier': oauth_verifier, 'oauth_token': request_token}, loop=loop) self.oauth_token = data.get('oauth_token') self.oauth_token_secret = data.get('oauth_token_secret') return self.oauth_token, self.oauth_token_secret, data
async def get_access_token(self, oauth_verifier, request_token=None, loop=None, **params)
Get access_token from OAuth1 provider. :returns: (access_token, access_token_secret, provider_data)
3.147875
3.082311
1.021271
params = dict(self.params, **params) params.update({'client_id': self.client_id, 'response_type': 'code'}) return self.authorize_url + '?' + urlencode(params)
def get_authorize_url(self, **params)
Return formatted authorize URL.
2.449919
2.204692
1.11123
url = self._get_url(url) params = params or {} access_token = access_token or self.access_token if access_token: if isinstance(params, list): if self.access_token_key not in dict(params): params.append((self.access_token_key, access_token)) else: params[self.access_token_key] = access_token headers = headers or { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', } return self._request(method, url, params=params, headers=headers, **aio_kwargs)
def request(self, method, url, params=None, headers=None, access_token=None, **aio_kwargs)
Request OAuth2 resource.
2.04028
1.934845
1.054492
# Possibility to provide REQUEST DATA to the method payload.setdefault('grant_type', 'authorization_code') payload.update({'client_id': self.client_id, 'client_secret': self.client_secret}) if not isinstance(code, str) and self.shared_key in code: code = code[self.shared_key] payload['refresh_token' if payload['grant_type'] == 'refresh_token' else 'code'] = code redirect_uri = redirect_uri or self.params.get('redirect_uri') if redirect_uri: payload['redirect_uri'] = redirect_uri self.access_token = None data = await self.request('POST', self.access_token_url, data=payload, loop=loop) try: self.access_token = data['access_token'] except KeyError: self.logger.error( 'Error when getting the access token.\nData returned by OAuth server: %r', data, ) raise web.HTTPBadRequest(reason='Failed to obtain OAuth access token.') return self.access_token, data
async def get_access_token(self, code, loop=None, redirect_uri=None, **payload)
Get an access_token from OAuth provider. :returns: (access_token, provider_data)
3.183045
3.147696
1.01123
user_ = data.get('user') yield 'id', user_.get('username') yield 'username', user_.get('username') yield 'first_name', user_.get('first_name') yield 'last_name', user_.get('last_name') yield 'picture', user_.get('avatar') yield 'link', user_.get('resource_url')
def user_parse(data)
Parse information from the provider.
2.673822
2.576156
1.037912
yield 'id', data.get('uuid') yield 'username', data.get('username') yield 'last_name', data.get('display_name') links = data.get('links', {}) yield 'picture', links.get('avatar', {}).get('href') yield 'link', links.get('html', {}).get('href')
def user_parse(data)
Parse information from the provider.
2.902391
2.757588
1.052511
auth = None access_token = params.pop(self.access_token_key, None) if access_token: headers['Authorization'] = "Bearer %s" % access_token else: auth = BasicAuth(self.client_id, self.client_secret) return super(Bitbucket2Client, self)._request( method, url, headers=headers, params=params, auth=auth, **aio_kwargs)
def _request(self, method, url, headers=None, params=None, **aio_kwargs)
Setup Authorization Header..
2.630574
2.383133
1.10383
yield 'id', data.get('id') yield 'username', data.get('username') yield 'discriminator', data.get('discriminator') yield 'picture', "https://cdn.discordapp.com/avatars/{}/{}.png".format( data.get('id'), data.get('avatar'))
def user_parse(data)
Parse information from the provider.
2.602435
2.517937
1.033558
access_token = params.pop(self.access_token_key, None) if access_token: headers['Authorization'] = "Bearer %s" % access_token return super(DiscordClient, self)._request( method, url, headers=headers, params=params, **aio_kwargs)
def _request(self, method, url, headers=None, params=None, **aio_kwargs)
Setup Authorization Header..
2.618416
2.306433
1.135267
user_ = data.get('user', {}) yield 'id', data.get('user_nsid') or user_.get('id') yield 'username', user_.get('username', {}).get('_content') first_name, _, last_name = data.get( 'fullname', {}).get('_content', '').partition(' ') yield 'first_name', first_name yield 'last_name', last_name
def user_parse(data)
Parse information from the provider.
3.544078
3.412818
1.038461
_user = data.get('user_info', {}) _id = _user.get('id') or _user.get('uid') yield 'id', _id yield 'locale', _user.get('default_lang') yield 'username', _user.get('display_name') first_name, _, last_name = _user.get('full_name', '').partition(' ') yield 'first_name', first_name yield 'last_name', last_name yield 'picture', 'http://avatars.plurk.com/{0}-big2.jpg'.format(_id) city, country = map(lambda s: s.strip(), _user.get('location', ',').split(',')) yield 'city', city yield 'country', country
def user_parse(data)
Parse information from the provider.
2.942869
2.847643
1.03344
yield 'id', data.get('id') or data.get('user_id') first_name, _, last_name = data['name'].partition(' ') yield 'first_name', first_name yield 'last_name', last_name yield 'picture', data.get('profile_image_url') yield 'locale', data.get('lang') yield 'link', data.get('url') yield 'username', data.get('screen_name') city, _, country = map(lambda s: s.strip(), data.get('location', '').partition(',')) yield 'city', city yield 'country', country
def user_parse(data)
Parse information from the provider.
2.226554
2.183942
1.019512
_user = data.get('response', {}).get('user', {}) yield 'id', _user.get('name') yield 'username', _user.get('name') yield 'link', _user.get('blogs', [{}])[0].get('url')
def user_parse(data)
Parse information from the provider.
4.068126
3.913401
1.039537
_user = data.get('oauth', {}).get('user', {}) yield 'id', _user.get('id') yield 'username', _user.get('username') first_name, _, last_name = _user.get('display_name').partition(' ') yield 'first_name', first_name yield 'last_name', last_name
def user_parse(data)
Parse information from the provider.
2.652337
2.540226
1.044134
_user = data.get('query', {}).get('results', {}).get('profile', {}) yield 'id', _user.get('guid') yield 'username', _user.get('username') yield 'link', _user.get('profileUrl') emails = _user.get('emails') if isinstance(emails, list): for email in emails: if 'primary' in list(email.keys()): yield 'email', email.get('handle') elif isinstance(emails, dict): yield 'email', emails.get('handle') yield 'picture', _user.get('image', {}).get('imageUrl') city, country = map(lambda s: s.strip(), _user.get('location', ',').split(',')) yield 'city', city yield 'country', country
def user_parse(data)
Parse information from the provider.
2.686149
2.644694
1.015675
for email in data.get('emails', []): if email.get('primary'): yield 'id', email.get('email') yield 'email', email.get('email') break
def user_parse(data)
Parse information from provider.
3.810946
3.477976
1.095737
params = params or {} params[ 'fields'] = 'id,email,first_name,last_name,name,link,locale,' \ 'gender,location' return await super(FacebookClient, self).user_info(params=params, **kwargs)
async def user_info(self, params=None, **kwargs)
Facebook required fields-param.
4.343347
3.249893
1.336459
id_ = data.get('id') yield 'id', id_ yield 'email', data.get('email') yield 'first_name', data.get('first_name') yield 'last_name', data.get('last_name') yield 'username', data.get('name') yield 'picture', 'http://graph.facebook.com/{0}/picture?' \ 'type=large'.format(id_) yield 'link', data.get('link') yield 'locale', data.get('locale') yield 'gender', data.get('gender') location = data.get('location', {}).get('name') if location: split_location = location.split(', ') yield 'city', split_location[0].strip() if len(split_location) > 1: yield 'country', split_location[1].strip()
def user_parse(data)
Parse information from provider.
1.933721
1.905452
1.014836
user = data.get('response', {}).get('user', {}) yield 'id', user.get('id') yield 'email', user.get('contact', {}).get('email') yield 'first_name', user.get('firstName') yield 'last_name', user.get('lastName') city, country = user.get('homeCity', ', ').split(', ') yield 'city', city yield 'country', country
def user_parse(data)
Parse information from the provider.
2.701617
2.639443
1.023556
yield 'id', data.get('id') yield 'email', data.get('email') first_name, _, last_name = (data.get('name') or '').partition(' ') yield 'first_name', first_name yield 'last_name', last_name yield 'username', data.get('login') yield 'picture', data.get('avatar_url') yield 'link', data.get('html_url') location = data.get('location', '') if location: split_location = location.split(',') yield 'country', split_location[0].strip() if len(split_location) > 1: yield 'city', split_location[1].strip()
def user_parse(data)
Parse information from provider.
1.947439
1.912253
1.0184
yield 'id', data.get('id') yield 'email', data.get('email') yield 'first_name', data.get('given_name') yield 'last_name', data.get('family_name') yield 'link', data.get('link') yield 'locale', data.get('locale') yield 'picture', data.get('picture') yield 'gender', data.get('gender')
def user_parse(data)
Parse information from provider.
1.806637
1.745896
1.03479
resp = data.get('response', [{}])[0] yield 'id', resp.get('uid') yield 'first_name', resp.get('first_name') yield 'last_name', resp.get('last_name') yield 'username', resp.get('nickname') yield 'city', resp.get('city') yield 'country', resp.get('country') yield 'picture', resp.get('photo_big')
def user_parse(data)
Parse information from provider.
2.474997
2.4414
1.013762
required_methods = ['POST'] if hijack_settings.HIJACK_ALLOW_GET_REQUESTS: required_methods.append('GET') return require_http_methods(required_methods)(fn)
def hijack_require_http_methods(fn)
Wrapper for "require_http_methods" decorator. POST required by default, GET can optionally be allowed
3.362694
2.812425
1.195656
kw = {'receiver': update_last_login} kw_id = {'receiver': update_last_login, 'dispatch_uid': 'update_last_login'} was_connected = user_logged_in.disconnect(**kw) was_connected_id = not was_connected and user_logged_in.disconnect(**kw_id) yield # Restore signal if needed if was_connected: user_logged_in.connect(**kw) elif was_connected_id: user_logged_in.connect(**kw_id)
def no_update_last_login()
Disconnect any signals to update_last_login() for the scope of the context manager, then restore.
3.645141
3.06431
1.189547
if hijacker.is_superuser: return True if hijacked.is_superuser: return False if hijacker.is_staff and hijack_settings.HIJACK_AUTHORIZE_STAFF: if hijacked.is_staff and not hijack_settings.HIJACK_AUTHORIZE_STAFF_TO_HIJACK_STAFF: return False return True return False
def is_authorized_default(hijacker, hijacked)
Checks if the user has the correct permission to Hijack another user. By default only superusers are allowed to hijack. An exception is made to allow staff members to hijack when HIJACK_AUTHORIZE_STAFF is enabled in the Django settings. By default it prevents staff users from hijacking other staff users. This can be disabled by enabling the HIJACK_AUTHORIZE_STAFF_TO_HIJACK_STAFF setting in the Django settings. Staff users can never hijack superusers.
2.753751
1.870789
1.471973
''' Evaluates the authorization check specified in settings ''' authorization_check = import_string(hijack_settings.HIJACK_AUTHORIZATION_CHECK) return authorization_check(hijack, hijacked)
def is_authorized(hijack, hijacked)
Evaluates the authorization check specified in settings
6.408622
3.774178
1.698018
''' hijack mechanism ''' hijacker = request.user hijack_history = [request.user._meta.pk.value_to_string(hijacker)] if request.session.get('hijack_history'): hijack_history = request.session['hijack_history'] + hijack_history check_hijack_authorization(request, hijacked) backend = get_used_backend(request) hijacked.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) with no_update_last_login(): # Actually log user in login(request, hijacked) hijack_started.send( sender=None, request=request, hijacker=hijacker, hijacked=hijacked, # send IDs for backward compatibility hijacker_id=hijacker.pk, hijacked_id=hijacked.pk) request.session['hijack_history'] = hijack_history request.session['is_hijacked_user'] = True request.session['display_hijack_warning'] = True request.session.modified = True return redirect_to_next(request, default_url=hijack_settings.HIJACK_LOGIN_REDIRECT_URL)
def login_user(request, hijacked)
hijack mechanism
3.19735
3.139231
1.018514
''' Checks whether the response object is a html page or a likely downloadable file. Intended to detect error pages or prompts such as kaggle's competition rules acceptance prompt. Returns True if the response is a html page. False otherwise. ''' content_type = response.headers.get('Content-Type', '') content_disp = response.headers.get('Content-Disposition', '') if 'text/html' in content_type and 'attachment' not in content_disp: # This response is a html file # which is not marked as an attachment, # so we likely hit a rules acceptance prompt return False return True
def is_downloadable(self, response)
Checks whether the response object is a html page or a likely downloadable file. Intended to detect error pages or prompts such as kaggle's competition rules acceptance prompt. Returns True if the response is a html page. False otherwise.
7.270679
2.560446
2.839614
self.request_params.update({'sysparm_count': True}) response = self.session.get(self._get_stats_url(), params=self._get_formatted_query(fields=list(), limit=None, order_by=list(), offset=None)) content = self._get_content(response) return int(content['stats']['count'])
def count(self)
Returns the number of records the query would yield
5.988214
5.596115
1.070066
response = self.session.get(self._get_table_url(), params=self._get_formatted_query(fields, limit, order_by, offset)) yield self._get_content(response) while 'next' in response.links: self.url_link = response.links['next']['url'] response = self.session.get(self.url_link) yield self._get_content(response)
def _all_inner(self, fields, limit, order_by, offset)
Yields all records for the query and follows links if present on the response after validating :return: List of records with content
2.854423
2.837837
1.005845
warnings.warn("get_all() is deprecated, please use get_multiple() instead", DeprecationWarning) return self.get_multiple(fields, limit, order_by, offset)
def get_all(self, fields=list(), limit=None, order_by=list(), offset=None)
DEPRECATED - see get_multiple()
2.702385
1.927367
1.402112
return itertools.chain.from_iterable(self._all_inner(fields, limit, order_by, offset))
def get_multiple(self, fields=list(), limit=None, order_by=list(), offset=None)
Wrapper method that takes whatever was returned by the _all_inner() generators and chains it in one result The response can be sorted by passing a list of fields to order_by. Example: get_multiple(order_by=['category', '-created_on']) would sort the category field in ascending order, with a secondary sort by created_on in descending order. :param fields: List of fields to return in the result :param limit: Limits the number of records returned :param order_by: Sort response based on certain fields :param offset: A number of records to skip before returning records (for pagination) :return: - Iterable chain object
6.590036
4.155838
1.58573
response = self.session.get(self._get_table_url(), params=self._get_formatted_query(fields, limit=None, order_by=list(), offset=None)) content = self._get_content(response) l = len(content) if l > 1: raise MultipleResults('Multiple results for get_one()') if len(content) == 0: return {} return content[0]
def get_one(self, fields=list())
Convenience function for queries returning only one result. Validates response before returning. :param fields: List of fields to return in the result :raise: :MultipleResults: if more than one match is found :return: - Record content
4.337469
4.170529
1.040028
response = self.session.post(self._get_table_url(), data=json.dumps(payload)) return self._get_content(response)
def insert(self, payload)
Inserts a new record with the payload passed as an argument :param payload: The record to create (dict) :return: - Created record
4.601602
5.737537
0.802017
try: result = self.get_one() if 'sys_id' not in result: raise NoResults() except MultipleResults: raise MultipleResults("Deletion of multiple records is not supported") except NoResults as e: e.args = ('Cannot delete a non-existing record',) raise response = self.session.delete(self._get_table_url(sys_id=result['sys_id'])) return self._get_content(response)
def delete(self)
Deletes the queried record and returns response content after response validation :raise: :NoResults: if query returned no results :NotImplementedError: if query returned more than one result (currently not supported) :return: - Delete response content (Generally always {'Success': True})
4.715175
4.224204
1.116228
try: result = self.get_one() if 'sys_id' not in result: raise NoResults() except MultipleResults: raise MultipleResults("Update of multiple records is not supported") except NoResults as e: e.args = ('Cannot update a non-existing record',) raise if not isinstance(payload, dict): raise InvalidUsage("Update payload must be of type dict") response = self.session.put(self._get_table_url(sys_id=result['sys_id']), data=json.dumps(payload)) return self._get_content(response)
def update(self, payload)
Updates the queried record with `payload` and returns the updated record after validating the response :param payload: Payload to update the record with :raise: :NoResults: if query returned no results :MultipleResults: if query returned more than one result (currently not supported) :return: - The updated record
4.206558
3.75635
1.119852
if not isinstance(reset_fields, list): raise InvalidUsage("reset_fields must be a `list` of fields") try: response = self.get_one() if 'sys_id' not in response: raise NoResults() except MultipleResults: raise MultipleResults('Cloning multiple records is not supported') except NoResults as e: e.args = ('Cannot clone a non-existing record',) raise payload = {} # Iterate over fields in the result for field in response: # Ignore fields in reset_fields if field in reset_fields: continue item = response[field] # Check if the item is of type dict and has a sys_id ref (value) if isinstance(item, dict) and 'value' in item: payload[field] = item['value'] else: payload[field] = item try: return self.insert(payload) except UnexpectedResponse as e: if e.status_code == 403: # User likely attempted to clone a record without resetting a unique field e.args = ('Unable to create clone. Make sure unique fields has been reset.',) raise
def clone(self, reset_fields=list())
Clones the queried record :param reset_fields: Fields to reset :raise: :NoResults: if query returned no results :MultipleResults: if query returned more than one result (currently not supported) :UnexpectedResponse: informs the user about what likely went wrong :return: - The cloned record
4.262192
3.730208
1.142615
try: result = self.get_one() if 'sys_id' not in result: raise NoResults() except MultipleResults: raise MultipleResults('Attaching a file to multiple records is not supported') except NoResults: raise NoResults('Attempted to attach file to a non-existing record') if not os.path.isfile(file): raise InvalidUsage("Attachment '%s' must be an existing regular file" % file) response = self.session.post( self._get_attachment_url('upload'), data={ 'table_name': self.table, 'table_sys_id': result['sys_id'], 'file_name': ntpath.basename(file) }, files={'file': open(file, 'rb')}, headers={'content-type': None} # Temporarily override header ) return self._get_content(response)
def attach(self, file)
Attaches the queried record with `file` and returns the response after validating the response :param file: File to attach to the record :raise: :NoResults: if query returned no results :MultipleResults: if query returned more than one result (currently not supported) :return: - The attachment record metadata
3.844408
3.477478
1.105516
method = response.request.method self.last_response = response server_error = { 'summary': None, 'details': None } try: content_json = response.json() if 'error' in content_json: e = content_json['error'] if 'message' in e: server_error['summary'] = e['message'] if 'detail' in e: server_error['details'] = e['detail'] except ValueError: content_json = {} if method == 'DELETE': # Make sure the delete operation returned the expected response if response.status_code == 204: return {'success': True} else: raise UnexpectedResponse( 204, response.status_code, method, server_error['summary'], server_error['details'] ) # Make sure the POST operation returned the expected response elif method == 'POST' and response.status_code != 201: raise UnexpectedResponse( 201, response.status_code, method, server_error['summary'], server_error['details'] ) # It seems that Helsinki and later returns status 200 instead of 404 on empty result sets if ('result' in content_json and len(content_json['result']) == 0) or response.status_code == 404: if self.raise_on_empty is True: raise NoResults('Query yielded no results') elif 'error' in content_json: raise UnexpectedResponse( 200, response.status_code, method, server_error['summary'], server_error['details'] ) if 'result' not in content_json: raise MissingResult("The request was successful but the content didn't contain the expected 'result'") return content_json['result']
def _get_content(self, response)
Checks for errors in the response. Returns response content, in bytes. :param response: response object :raise: :UnexpectedResponse: if the server responded with an unexpected response :return: - ServiceNow response content
2.699351
2.734523
0.987138
url_str = '%(base_url)s/%(base_path)s/%(resource)s/%(item)s' % ( { 'base_url': self.base_url, 'base_path': self.base_path, 'resource': resource, 'item': item } ) if sys_id: return "%s/%s" % (url_str, sys_id) return url_str
def _get_url(self, resource, item, sys_id=None)
Takes table and sys_id (if present), and returns a URL :param resource: API resource :param item: API resource item :param sys_id: Record sys_id :return: - url string
1.954059
2.021113
0.966823
if not isinstance(order_by, list): raise InvalidUsage("Argument order_by should be a `list` of fields") if not isinstance(fields, list): raise InvalidUsage("Argument fields should be a `list` of fields") if isinstance(self.query, QueryBuilder): sysparm_query = str(self.query) elif isinstance(self.query, dict): # Dict-type query sysparm_query = '^'.join(['%s=%s' % (k, v) for k, v in six.iteritems(self.query)]) elif isinstance(self.query, six.string_types): # String-type query sysparm_query = self.query else: raise InvalidUsage("Query must be instance of %s, %s or %s" % (QueryBuilder, str, dict)) for field in order_by: if field[0] == '-': sysparm_query += "^ORDERBYDESC%s" % field[1:] else: sysparm_query += "^ORDERBY%s" % field params = {'sysparm_query': sysparm_query} params.update(self.request_params) if limit is not None: params.update({'sysparm_limit': limit, 'sysparm_suppress_pagination_header': True}) if offset is not None: params.update({'sysparm_offset': offset}) if len(fields) > 0: params.update({'sysparm_fields': ",".join(fields)}) return params
def _get_formatted_query(self, fields, limit, order_by, offset)
Converts the query to a ServiceNow-interpretable format :return: - ServiceNow query
2.23321
2.233587
0.999831
if not session: logger.debug('(SESSION_CREATE) User: %s' % self._user) s = requests.Session() s.auth = HTTPBasicAuth(self._user, self._password) else: logger.debug('(SESSION_CREATE) Object: %s' % session) s = session s.headers.update( { 'content-type': 'application/json', 'accept': 'application/json', 'User-Agent': 'pysnow/%s' % pysnow.__version__ } ) return s
def _get_session(self, session)
Creates a new session with basic auth, unless one was provided, and sets headers. :param session: (optional) Session to re-use :return: - :class:`requests.Session` object
3.082675
2.866623
1.075368
warnings.warn("`%s` is deprecated and will be removed in a future release. " "Please use `resource()` instead." % inspect.stack()[1][3], DeprecationWarning) return LegacyRequest(method, table, request_params=self.request_params, raise_on_empty=self.raise_on_empty, session=self.session, instance=self.instance, base_url=self.base_url, **kwargs)
def _legacy_request(self, method, table, **kwargs)
Returns a :class:`LegacyRequest` object, compatible with Client.query and Client.insert :param method: HTTP method :param table: Table to operate on :return: - :class:`LegacyRequest` object
3.417233
3.672452
0.930504
for path in [api_path, base_path]: URLBuilder.validate_path(path) return Resource(api_path=api_path, base_path=base_path, parameters=self.parameters, chunk_size=chunk_size or 8192, session=self.session, base_url=self.base_url, **kwargs)
def resource(self, api_path=None, base_path='/api/now', chunk_size=None, **kwargs)
Creates a new :class:`Resource` object after validating paths :param api_path: Path to the API to operate on :param base_path: (optional) Base path override :param chunk_size: Response stream parser chunk size (in bytes) :param **kwargs: Pass request.request parameters to the Resource object :return: - :class:`Resource` object :raises: - InvalidUsage: If a path fails validation
3.090634
3.320817
0.930685
r = self._legacy_request('POST', table, **kwargs) return r.insert(payload)
def insert(self, table, payload, **kwargs)
Insert (POST) request wrapper :param table: table to insert on :param payload: update payload (dict) :param kwargs: Keyword arguments passed along to `Request` :return: - Dictionary containing the created record
10.961411
12.730645
0.861026
params = self._parameters.as_dict() use_stream = kwargs.pop('stream', False) logger.debug('(REQUEST_SEND) Method: %s, Resource: %s' % (method, self._resource)) response = self._session.request(method, self._url, stream=use_stream, params=params, **kwargs) response.raw.decode_content = True logger.debug('(RESPONSE_RECEIVE) Code: %d, Resource: %s' % (response.status_code, self._resource)) return Response(response=response, resource=self._resource, chunk_size=self._chunk_size, stream=use_stream)
def _get_response(self, method, **kwargs)
Response wrapper - creates a :class:`requests.Response` object and passes along to :class:`pysnow.Response` for validation and parsing. :param args: args to pass along to _send() :param kwargs: kwargs to pass along to _send() :return: - :class:`pysnow.Response` object
3.23684
3.245398
0.997363
self._parameters.query = kwargs.pop('query', {}) if len(args) == 0 else args[0] self._parameters.limit = kwargs.pop('limit', 10000) self._parameters.offset = kwargs.pop('offset', 0) self._parameters.fields = kwargs.pop('fields', kwargs.pop('fields', [])) return self._get_response('GET', stream=kwargs.pop('stream', False))
def get(self, *args, **kwargs)
Fetches one or more records :return: - :class:`pysnow.Response` object
2.969883
3.001245
0.98955
if not isinstance(payload, dict): raise InvalidUsage("Update payload must be of type dict") record = self.get(query).one() self._url = self._url_builder.get_appended_custom("/{0}".format(record['sys_id'])) return self._get_response('PUT', data=json.dumps(payload))
def update(self, query, payload)
Updates a record :param query: Dictionary, string or :class:`QueryBuilder` object :param payload: Dictionary payload :return: - Dictionary of the updated record
7.198277
6.94061
1.037125
record = self.get(query=query).one() self._url = self._url_builder.get_appended_custom("/{0}".format(record['sys_id'])) return self._get_response('DELETE').one()
def delete(self, query)
Deletes a record :param query: Dictionary, string or :class:`QueryBuilder` object :return: - Dictionary containing status of the delete operation
12.574954
13.552477
0.927871
if headers: self._session.headers.update(headers) if path_append is not None: try: self._url = self._url_builder.get_appended_custom(path_append) except InvalidUsage: raise InvalidUsage("Argument 'path_append' must be a string in the following format: " "/path-to-append[/.../...]") return self._get_response(method, **kwargs)
def custom(self, method, path_append=None, headers=None, **kwargs)
Creates a custom request :param method: HTTP method :param path_append: (optional) append path to resource.api_path :param headers: (optional) Dictionary of headers to add or override :param kwargs: kwargs to pass along to :class:`requests.Request` :return: - :class:`pysnow.Response` object
5.144891
5.489801
0.937173
resource = copy(self) resource._url_builder = URLBuilder(self._base_url, self._base_path, '/attachment') path = self._api_path.strip('/').split('/') if path[0] != 'table': raise InvalidUsage('The attachment API can only be used with the table API') return Attachment(resource, path[1])
def attachments(self)
Provides an `Attachment` API for this resource. Enables easy listing, deleting and creating new attachments. :return: Attachment object
8.16955
6.518439
1.253299
parameters = copy(self.parameters) return SnowRequest(url_builder=self._url_builder, parameters=parameters, resource=self, **self.kwargs)
def _request(self)
Request wrapper :return: SnowRequest object
13.630861
10.142545
1.343929
return self._request.custom(method, path_append=path_append, headers=headers, **kwargs)
def request(self, method, path_append=None, headers=None, **kwargs)
Create a custom request :param method: HTTP method to use :param path_append: (optional) relative to :attr:`api_path` :param headers: (optional) Dictionary of headers to add or override :param kwargs: kwargs to pass along to :class:`requests.Request` :return: - :class:`Response` object
5.067134
6.166377
0.821736
response = self._get_response() has_result_single = False has_result_many = False has_error = False builder = ObjectBuilder() for prefix, event, value in ijson.parse(response.raw, buf_size=self._chunk_size): if (prefix, event) == ('error', 'start_map'): # Matched ServiceNow `error` object at the root has_error = True elif prefix == 'result' and event in ['start_map', 'start_array']: # Matched ServiceNow `result` if event == 'start_map': # Matched object has_result_single = True elif event == 'start_array': # Matched array has_result_many = True if has_result_many: # Build the result if (prefix, event) == ('result.item', 'end_map'): # Reached end of object. Set count and yield builder.event(event, value) self.count += 1 yield getattr(builder, 'value') elif prefix.startswith('result.item'): # Build the result object builder.event(event, value) elif has_result_single: if (prefix, event) == ('result', 'end_map'): # Reached end of the result object. Set count and yield. builder.event(event, value) self.count += 1 yield getattr(builder, 'value') elif prefix.startswith('result'): # Build the error object builder.event(event, value) elif has_error: if (prefix, event) == ('error', 'end_map'): # Reached end of the error object - raise ResponseError exception raise ResponseError(getattr(builder, 'value')) elif prefix.startswith('error'): # Build the error object builder.event(event, value) if (has_result_single or has_result_many) and self.count == 0: # Results empty return if not (has_result_single or has_result_many or has_error): # None of the expected keys were found raise MissingResult('The expected `result` key was missing in the response. Cannot continue')
def _parse_response(self)
Looks for `result.item` (array), `result` (object) and `error` (object) keys and parses the raw response content (stream of bytes) :raise: - ResponseError: If there's an error in the response - MissingResult: If no result nor error was found
3.238671
2.962059
1.093385
response = self._get_response() if response.request.method == 'DELETE' and response.status_code == 204: return [{'status': 'record deleted'}], 1 result = self._response.json().get('result', None) if result is None: raise MissingResult('The expected `result` key was missing in the response. Cannot continue') length = 0 if isinstance(result, list): length = len(result) elif isinstance(result, dict): result = [result] length = 1 return result, length
def _get_buffered_response(self)
Returns a buffered response :return: Buffered response
4.140955
4.068384
1.017838
if self._stream: return chain.from_iterable(self._get_streamed_response()) return self._get_buffered_response()[0]
def all(self)
Returns a chained generator response containing all matching records :return: - Iterable response
11.004041
8.376144
1.313736
if not self._stream: raise InvalidUsage('first() is only available when stream=True') try: content = next(self.all()) except StopIteration: raise NoResults("No records found") return content
def first(self)
Return the first record or raise an exception if the result doesn't contain any data :return: - Dictionary containing the first item in the response content :raise: - NoResults: If no results were found
9.359818
6.138846
1.524687
result, count = self._get_buffered_response() if count == 0: raise NoResults("No records found") elif count > 1: raise MultipleResults("Expected single-record result, got multiple") return result[0]
def one(self)
Return exactly one record or raise an exception. :return: - Dictionary containing the only item in the response content :raise: - MultipleResults: If more than one records are present in the content - NoResults: If the result is empty
6.517983
4.634712
1.40634
return self._resource.attachments.upload(self['sys_id'], *args, **kwargs)
def upload(self, *args, **kwargs)
Convenience method for attaching files to a fetched record :param args: args to pass along to `Attachment.upload` :param kwargs: kwargs to pass along to `Attachment.upload` :return: upload response object
14.745191
9.834033
1.499404
if sys_id: return self.resource.get(query={'table_sys_id': sys_id, 'table_name': self.table_name}).all() return self.resource.get(query={'table_name': self.table_name}, limit=limit).all()
def get(self, sys_id=None, limit=100)
Returns a list of attachments :param sys_id: record sys_id to list attachments for :param limit: override the default limit of 100 :return: list of attachments
3.122478
3.389932
0.921103
if not isinstance(multipart, bool): raise InvalidUsage('Multipart must be of type bool') resource = self.resource if name is None: name = os.path.basename(file_path) resource.parameters.add_custom({ 'table_name': self.table_name, 'table_sys_id': sys_id, 'file_name': name }) data = open(file_path, 'rb').read() headers = {} if multipart: headers["Content-Type"] = "multipart/form-data" path_append = '/upload' else: headers["Content-Type"] = "text/plain" path_append = '/file' return resource.request(method='POST', data=data, headers=headers, path_append=path_append)
def upload(self, sys_id, file_path, name=None, multipart=False)
Attaches a new file to the provided record :param sys_id: the sys_id of the record to attach the file to :param file_path: local absolute path of the file to upload :param name: custom name for the uploaded file (instead of basename) :param multipart: whether or not to use multipart :return: the inserted record
2.781291
2.807394
0.990702
if not isinstance(path, six.string_types) or not re.match('^/(?:[._a-zA-Z0-9-]/?)+[^/]$', path): raise InvalidUsage( "Path validation failed - Expected: '/<component>[/component], got: %s" % path ) return True
def validate_path(path)
Validates the provided path :param path: path to validate (string) :raise: :InvalidUsage: If validation fails.
8.098378
6.695759
1.209479
if instance is not None: host = ("%s.service-now.com" % instance).rstrip('/') if use_ssl is True: return "https://%s" % host return "http://%s" % host
def get_base_url(use_ssl, instance=None, host=None)
Formats the base URL either `host` or `instance` :return: Base URL string
3.392632
3.216224
1.054849
return self._get_session( OAuth2Session( client_id=self.client_id, token=self.token, token_updater=self.token_updater, auto_refresh_url=self.token_url, auto_refresh_kwargs={ "client_id": self.client_id, "client_secret": self.client_secret } ) )
def _get_oauth_session(self)
Creates a new OAuth session :return: - OAuth2Session object
1.923397
1.92451
0.999422
if not token: self.token = None return expected_keys = ['token_type', 'refresh_token', 'access_token', 'scope', 'expires_in', 'expires_at'] if not isinstance(token, dict) or not set(token) >= set(expected_keys): raise InvalidUsage("Expected a token dictionary containing the following keys: {0}" .format(expected_keys)) # Set sanitized token self.token = dict((k, v) for k, v in token.items() if k in expected_keys)
def set_token(self, token)
Validate and set token :param token: the token (dict) to set
3.010264
2.819428
1.067686
if isinstance(self.token, dict): self.session = self._get_oauth_session() return super(OAuthClient, self)._legacy_request(*args, **kwargs) raise MissingToken("You must set_token() before creating a legacy request with OAuthClient")
def _legacy_request(self, *args, **kwargs)
Makes sure token has been set, then calls parent to create a new :class:`pysnow.LegacyRequest` object :param args: args to pass along to _legacy_request() :param kwargs: kwargs to pass along to _legacy_request() :return: - :class:`pysnow.LegacyRequest` object :raises: - MissingToken: If token hasn't been set
6.937826
5.226608
1.327405
if isinstance(self.token, dict): self.session = self._get_oauth_session() return super(OAuthClient, self).resource(api_path, base_path, chunk_size) raise MissingToken("You must set_token() before creating a resource with OAuthClient")
def resource(self, api_path=None, base_path='/api/now', chunk_size=None)
Overrides :meth:`resource` provided by :class:`pysnow.Client` with extras for OAuth :param api_path: Path to the API to operate on :param base_path: (optional) Base path override :param chunk_size: Response stream parser chunk size (in bytes) :return: - :class:`Resource` object :raises: - InvalidUsage: If a path fails validation
5.202959
5.54845
0.937732
logger.debug('(TOKEN_CREATE) :: User: %s' % user) session = OAuth2Session(client=LegacyApplicationClient(client_id=self.client_id)) try: return dict(session.fetch_token(token_url=self.token_url, username=user, password=password, client_id=self.client_id, client_secret=self.client_secret)) except OAuth2Error as exception: raise TokenCreateError('Error creating user token', exception.description, exception.status_code)
def generate_token(self, user, password)
Takes user and password credentials and generates a new token :param user: user :param password: password :return: - dictionary containing token data :raises: - TokenCreateError: If there was an error generating the new token
3.434588
3.142331
1.093006
self._query.append('ORDERBYDESC{0}'.format(self.current_field)) self.c_oper = inspect.currentframe().f_back.f_code.co_name return self
def order_descending(self)
Sets ordering of field descending
8.692657
6.785812
1.281005
if isinstance(data, six.string_types): return self._add_condition('=', data, types=[int, str]) elif isinstance(data, list): return self._add_condition('IN', ",".join(map(str, data)), types=[str]) raise QueryTypeError('Expected value of type `str` or `list`, not %s' % type(data))
def equals(self, data)
Adds new `IN` or `=` condition depending on if a list or string was provided :param data: string or list of values :raise: - QueryTypeError: if `data` is of an unexpected type
4.066035
3.106522
1.308871
if hasattr(greater_than, 'strftime'): greater_than = datetime_as_utc(greater_than).strftime('%Y-%m-%d %H:%M:%S') elif isinstance(greater_than, six.string_types): raise QueryTypeError('Expected value of type `int` or instance of `datetime`, not %s' % type(greater_than)) return self._add_condition('>', greater_than, types=[int, str])
def greater_than(self, greater_than)
Adds new `>` condition :param greater_than: str or datetime compatible object (naive UTC datetime or tz-aware datetime) :raise: - QueryTypeError: if `greater_than` is of an unexpected type
4.462278
3.325213
1.341953
if hasattr(less_than, 'strftime'): less_than = datetime_as_utc(less_than).strftime('%Y-%m-%d %H:%M:%S') elif isinstance(less_than, six.string_types): raise QueryTypeError('Expected value of type `int` or instance of `datetime`, not %s' % type(less_than)) return self._add_condition('<', less_than, types=[int, str])
def less_than(self, less_than)
Adds new `<` condition :param less_than: str or datetime compatible object (naive UTC datetime or tz-aware datetime) :raise: - QueryTypeError: if `less_than` is of an unexpected type
4.486162
3.424351
1.310076
if hasattr(start, 'strftime') and hasattr(end, 'strftime'): dt_between = ( 'javascript:gs.dateGenerate("%(start)s")' "@" 'javascript:gs.dateGenerate("%(end)s")' ) % { 'start': start.strftime('%Y-%m-%d %H:%M:%S'), 'end': end.strftime('%Y-%m-%d %H:%M:%S') } elif isinstance(start, int) and isinstance(end, int): dt_between = '%d@%d' % (start, end) else: raise QueryTypeError("Expected `start` and `end` of type `int` " "or instance of `datetime`, not %s and %s" % (type(start), type(end))) return self._add_condition('BETWEEN', dt_between, types=[str])
def between(self, start, end)
Adds new `BETWEEN` condition :param start: int or datetime compatible object (in SNOW user's timezone) :param end: int or datetime compatible object (in SNOW user's timezone) :raise: - QueryTypeError: if start or end arguments is of an invalid type
3.409886
3.006705
1.134094
if not self.current_field: raise QueryMissingField("Conditions requires a field()") elif not type(operand) in types: caller = inspect.currentframe().f_back.f_code.co_name raise QueryTypeError("Invalid type passed to %s() , expected: %s" % (caller, types)) elif self.c_oper: raise QueryMultipleExpressions("Expected logical operator after expression") self.c_oper = inspect.currentframe().f_back.f_code.co_name self._query.append("%(current_field)s%(operator)s%(operand)s" % { 'current_field': self.current_field, 'operator': operator, 'operand': operand }) return self
def _add_condition(self, operator, operand, types)
Appends condition to self._query after performing validation :param operator: operator (str) :param operand: operand :param types: allowed types :raise: - QueryMissingField: if a field hasn't been set - QueryMultipleExpressions: if a condition already has been set - QueryTypeError: if the value is of an unexpected type
4.355899
3.484604
1.250041
if not self.c_oper: raise QueryExpressionError("Logical operators must be preceded by an expression") self.current_field = None self.c_oper = None self.l_oper = inspect.currentframe().f_back.f_code.co_name self._query.append(operator) return self
def _add_logical_operator(self, operator)
Adds a logical operator in query :param operator: logical operator (str) :raise: - QueryExpressionError: if a expression hasn't been set
6.158046
4.979386
1.236708
if isinstance(query, QueryBuilder): # Get string-representation of the passed :class:`pysnow.QueryBuilder` object return str(query) elif isinstance(query, dict): # Dict-type query return '^'.join(['%s=%s' % (k, v) for k, v in six.iteritems(query)]) elif isinstance(query, six.string_types): # Regular string-type query return query else: raise InvalidUsage('Query must be of type string, dict or a QueryBuilder object')
def stringify_query(query)
Stringifies the query (dict or QueryBuilder) into a ServiceNow-compatible format :return: - ServiceNow-compatible string-type query
4.085275
3.713976
1.099973
if isinstance(params, dict) is False: raise InvalidUsage("custom parameters must be of type `dict`") self._custom_params.update(params)
def add_custom(self, params)
Adds new custom parameter after making sure it's of type dict. :param params: Dictionary containing one or more parameters
5.199414
5.91127
0.879576
if not (isinstance(value, bool) or value == 'all'): raise InvalidUsage("Display value can be of type bool or value 'all'") self._sysparms['sysparm_display_value'] = value
def display_value(self, value)
Sets `sysparm_display_value` :param value: Bool or 'all'
9.171875
4.767828
1.923701
if not isinstance(limit, int) or isinstance(limit, bool): raise InvalidUsage("limit size must be of type integer") self._sysparms['sysparm_limit'] = limit
def limit(self, limit)
Sets `sysparm_limit` :param limit: Size limit (int)
7.973621
5.410416
1.473754
if not isinstance(offset, int) or isinstance(offset, bool): raise InvalidUsage('Offset must be an integer') self._sysparms['sysparm_offset'] = offset
def offset(self, offset)
Sets `sysparm_offset`, usually used to accomplish pagination :param offset: Number of records to skip before fetching records :raise: :InvalidUsage: if offset is of an unexpected type
5.925829
3.335087
1.776814
if not isinstance(fields, list): raise InvalidUsage('fields must be of type `list`') self._sysparms['sysparm_fields'] = ",".join(fields)
def fields(self, fields)
Sets `sysparm_fields` after joining the given list of `fields` :param fields: List of fields to include in the response :raise: :InvalidUsage: if fields is of an unexpected type
6.155833
2.990113
2.058729
if not isinstance(exclude, bool): raise InvalidUsage('exclude_reference_link must be of type bool') self._sysparms['sysparm_exclude_reference_link'] = exclude
def exclude_reference_link(self, exclude)
Sets `sysparm_exclude_reference_link` to a bool value :param exclude: bool
5.467224
4.354078
1.255656
if not isinstance(suppress, bool): raise InvalidUsage('suppress_pagination_header must be of type bool') self._sysparms['sysparm_suppress_pagination_header'] = suppress
def suppress_pagination_header(self, suppress)
Enables or disables pagination header by setting `sysparm_suppress_pagination_header` :param suppress: bool
4.923883
4.673095
1.053666
sysparms = self._sysparms sysparms.update(self._custom_params) return sysparms
def as_dict(self)
Constructs query params compatible with :class:`requests.Request` :return: - Dictionary containing query parameters
9.705703
9.110822
1.065294
def q(*args): raise urwid.ExitMainLoop() self.worker.shutdown(wait=False) self.ui_worker.shutdown(wait=False) self.loop.set_alarm_in(0, q)
def quit(self)
This could be called from another thread, so let's do this via alarm
5.745092
4.668594
1.230583
self.set_body(widget) self.reload_footer() if redraw: logger.debug("redraw main widget") self.refresh()
def _set_main_widget(self, widget, redraw)
add provided widget to widget list and display it :param widget: :return:
6.441223
8.276327
0.778271
logger.debug("display buffer %r", buffer) self.buffer_movement_history.append(buffer) self.current_buffer = buffer self._set_main_widget(buffer.widget, redraw=redraw)
def display_buffer(self, buffer, redraw=True)
display provided buffer :param buffer: Buffer :return:
5.993337
6.554884
0.914332
# FIXME: some buffers have arguments, do a proper comparison -- override __eq__ if buffer not in self.buffers: logger.debug("adding new buffer {!r}".format(buffer)) self.buffers.append(buffer) self.display_buffer(buffer, redraw=redraw)
def add_and_display_buffer(self, buffer, redraw=True)
add provided buffer to buffer list and display it :param buffer: :return:
7.010363
7.007564
1.000399
if len(self.buffers) == 1: # we don't need to display anything # listing is already displayed return else: try: self.display_buffer(self.buffers[i]) except IndexError: # i > len self.display_buffer(self.buffers[0])
def pick_and_display_buffer(self, i)
pick i-th buffer from list and display it :param i: int :return: None
4.215088
4.272074
0.986661
if self.prompt_bar: logger.info("prompt is active, won't build status bar") return try: left_widgets = self.current_buffer.build_status_bar() or [] except AttributeError: left_widgets = [] text_list = [] # FIXME: this code should be placed in buffer # TODO: display current active worker threads for idx, buffer in enumerate(self.buffers): # #1 [I] fedora #2 [L] fmt = "#{idx} [{name}]" markup = fmt.format(idx=idx, name=buffer.display_name) text_list.append(( "status_box_focus" if buffer == self.current_buffer else "status_box", markup, )) text_list.append(" ") text_list = text_list[:-1] if text_list: buffer_text = urwid.Text(text_list, align="right") else: buffer_text = urwid.Text("", align="right") columns = urwid.Columns(left_widgets + [buffer_text]) return urwid.AttrMap(columns, "status")
def build_statusbar(self)
construct and return statusbar widget
5.465868
5.340116
1.023549