Skip to content

Commit d3fd428

Browse files
authored
Merge pull request hpcugent#340 from stdweird/fix_rest
handle e.g. empty dict body data properly
2 parents 1ea3c61 + 444662b commit d3fd428

File tree

3 files changed

+34
-52
lines changed

3 files changed

+34
-52
lines changed

lib/vsc/utils/generaloption.py

Lines changed: 17 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def set_columns(cols=None):
6767
if cols is None:
6868
if os.path.exists(STTY):
6969
try:
70-
proc = subprocess.run(['/usr/bin/stty', 'size'], stdout=subprocess.PIPE)
70+
proc = subprocess.run(['/usr/bin/stty', 'size'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
7171
cols = str(proc.stdout.splitlines()[0].decode('utf-8').split(' ')[1])
7272
except (AttributeError, IndexError, OSError, ValueError):
7373
# do nothing
@@ -189,12 +189,12 @@ class ExtOption(CompleterOption):
189189

190190
def __init__(self, *args, **kwargs):
191191
"""Add logger to init"""
192-
CompleterOption.__init__(self, *args, **kwargs)
192+
super().__init__(*args, **kwargs)
193193
self.log = getLogger(self.__class__.__name__)
194194

195195
def _set_attrs(self, attrs):
196196
"""overwrite _set_attrs to allow store_or callbacks"""
197-
Option._set_attrs(self, attrs)
197+
super()._set_attrs(attrs)
198198
if self.action == 'extend':
199199
# alias
200200
self.action = 'add'
@@ -240,15 +240,15 @@ def process(self, opt, value, values, parser):
240240
self.log.raiseException("%s. Use '%s%s' if the value is correct." % (errmsg, prefix, value),
241241
exception=OptionValueError)
242242

243-
return Option.process(self, opt, value, values, parser)
243+
return super().process(opt, value, values, parser)
244244

245245
def take_action(self, action, dest, opt, value, values, parser):
246246
"""Extended take_action"""
247247
orig_action = action # keep copy
248248

249249
# dest is None for actions like shorthelp and confighelp
250250
if dest and getattr(parser._long_opt.get('--' + dest, ''), 'store_or', '') == 'help':
251-
Option.take_action(self, action, dest, opt, value, values, parser)
251+
super().take_action(action, dest, opt, value, values, parser)
252252
fn = getattr(parser, 'print_%shelp' % values.help, None)
253253
if fn is None:
254254
self.log.raiseException("Unsupported output format for help: %s" % value.help, exception=ValueError)
@@ -284,7 +284,7 @@ def take_action(self, action, dest, opt, value, values, parser):
284284
if hasattr(values, '_logaction_taken'):
285285
values._logaction_taken[dest] = True
286286

287-
Option.take_action(self, action, dest, opt, value, values, parser)
287+
super().take_action(action, dest, opt, value, values, parser)
288288

289289
elif action in self.EXTOPTION_EXTRA_OPTIONS:
290290
if action in ("add", "add_first", "add_flex",):
@@ -328,7 +328,7 @@ def take_action(self, action, dest, opt, value, values, parser):
328328
self.log.raiseException(msg % (action, self.EXTOPTION_EXTRA_OPTIONS))
329329
setattr(values, dest, lvalue)
330330
else:
331-
Option.take_action(self, action, dest, opt, value, values, parser)
331+
super().take_action(action, dest, opt, value, values, parser)
332332

333333
# set flag to mark as passed by action (ie not by default)
334334
# - distinguish from setting default value through option
@@ -345,12 +345,12 @@ class PassThroughOptionParser(OptionParser):
345345
from http://www.koders.com/python/fid9DFF5006AF4F52BA6483C4F654E26E6A20DBC73C.aspx?s=add+one#L27
346346
"""
347347
def __init__(self):
348-
OptionParser.__init__(self, add_help_option=False, usage=SUPPRESS_USAGE)
348+
super().__init__(add_help_option=False, usage=SUPPRESS_USAGE)
349349

350350
def _process_long_opt(self, rargs, values):
351351
"""Extend optparse code with catch of unknown long options error"""
352352
try:
353-
OptionParser._process_long_opt(self, rargs, values)
353+
super()._process_long_opt(rargs, values)
354354
except BadOptionError as err:
355355
self.largs.append(err.opt_str)
356356

@@ -411,13 +411,14 @@ def __init__(self, *args, **kwargs):
411411
if section_name in self.RESERVED_SECTIONS:
412412
self.log.raiseException('Cannot use reserved name %s for section name.' % section_name)
413413

414-
OptionGroup.__init__(self, *args, **kwargs)
414+
super().__init__(*args, **kwargs)
415+
415416
self.section_name = section_name
416417
self.section_options = []
417418

418419
def add_option(self, *args, **kwargs):
419420
"""Extract configfile section info"""
420-
option = OptionGroup.add_option(self, *args, **kwargs)
421+
option = super().add_option(*args, **kwargs)
421422
self.section_options.append(option)
422423

423424
return option
@@ -478,16 +479,9 @@ def __init__(self, *args, **kwargs):
478479
self.error_env_options = kwargs.pop('error_env_options', False)
479480
self.error_env_option_method = kwargs.pop('error_env_option_method', self.log.error)
480481

481-
# py2.4 epilog compatibilty with py2.7 / optparse 1.5.3
482-
self.epilog = kwargs.pop('epilog', None)
483-
484482
if 'option_class' not in kwargs:
485483
kwargs['option_class'] = ExtOption
486-
OptionParser.__init__(self, *args, **kwargs)
487-
488-
# redefine formatter for py2.4 compat
489-
if not hasattr(self.formatter, 'format_epilog'):
490-
setattr(self.formatter, 'format_epilog', self.formatter.format_description)
484+
super().__init__(*args, **kwargs)
491485

492486
if self.epilog is None:
493487
self.epilog = []
@@ -609,7 +603,7 @@ def format_description(self, formatter):
609603

610604
def set_usage(self, usage):
611605
"""Return usage and set try to set autogenerated description."""
612-
OptionParser.set_usage(self, usage)
606+
super().set_usage(usage)
613607

614608
if self.description is None:
615609
self.description = 'NONE_AND_NOT_NONE'
@@ -623,7 +617,7 @@ def get_default_values(self):
623617
- only works by using reference to object
624618
- same for _logaction_taken
625619
"""
626-
values = OptionParser.get_default_values(self)
620+
values = super().get_default_values()
627621

628622
class ExtValues(self.VALUES_CLASS):
629623
_action_taken = {}
@@ -633,19 +627,6 @@ class ExtValues(self.VALUES_CLASS):
633627
newvalues.__dict__ = values.__dict__.copy()
634628
return newvalues
635629

636-
def format_help(self, formatter=None):
637-
"""For py2.4 compatibility reasons (missing epilog). This is the py2.7 / optparse 1.5.3 code"""
638-
if formatter is None:
639-
formatter = self.formatter
640-
result = []
641-
if self.usage:
642-
result.append(self.get_usage() + "\n")
643-
if self.description:
644-
result.append(self.format_description(formatter) + "\n")
645-
result.append(self.format_option_help(formatter))
646-
result.append(self.format_epilog(formatter))
647-
return "".join(result)
648-
649630
def format_epilog(self, formatter):
650631
"""Allow multiple epilog parts"""
651632
res = []
@@ -694,7 +675,7 @@ def _is_enable_disable(x):
694675
def print_help(self, fh=None):
695676
"""Intercept print to file to print to string and remove the ENABLE/DISABLE options from help"""
696677
fh = self.check_help(fh)
697-
OptionParser.print_help(self, fh)
678+
super().print_help(fh)
698679

699680
def print_rsthelp(self, fh=None):
700681
""" Print help in rst format """
@@ -797,7 +778,7 @@ def _add_help_option(self):
797778

798779
def _get_args(self, args):
799780
"""Prepend the options set through the environment"""
800-
self.commandline_arguments = OptionParser._get_args(self, args)
781+
self.commandline_arguments = super()._get_args(args)
801782
self.get_env_options()
802783
return self.environment_arguments + self.commandline_arguments # prepend the environment options as longopts
803784

lib/vsc/utils/rest.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@
3838
import base64
3939
import copy
4040
import json
41+
import logging
4142
from functools import partial
42-
from vsc.utils import fancylogger
4343
from urllib.parse import urlencode
4444
from urllib.request import Request, HTTPSHandler, build_opener
4545

@@ -172,18 +172,19 @@ def request(self, method, url, body, headers, content_type=None):
172172
secret_items = ['Authorization', 'X-Auth-Token']
173173
headers_censored = self.censor_request(secret_items, headers)
174174

175-
if body and not isinstance(body, str):
176-
# censor contents of body to avoid leaking passwords
177-
secret_items = ['password']
178-
body_censored = self.censor_request(secret_items, body)
179-
# serialize body in all cases
180-
body = json.dumps(body)
181-
else:
182-
# assume serialized bodies are already clear of secrets
183-
fancylogger.getLogger().debug("Request with pre-serialized body, will not censor secrets")
184-
body_censored = body
175+
body_censored = body
176+
if body is not None:
177+
if isinstance(body, str):
178+
# assume serialized bodies are already clear of secrets
179+
logging.debug("Request with pre-serialized body, will not censor secrets")
180+
else:
181+
# censor contents of body to avoid leaking passwords
182+
secret_items = ['password']
183+
body_censored = self.censor_request(secret_items, body)
184+
# serialize body in all cases
185+
body = json.dumps(body)
185186

186-
fancylogger.getLogger().debug('cli request: %s, %s, %s, %s', method, url, body_censored, headers_censored)
187+
logging.debug('cli request: %s, %s, %s, %s', method, url, body_censored, headers_censored)
187188

188189
# TODO: in recent python: Context manager
189190
conn = self.get_connection(method, url, body, headers)
@@ -197,7 +198,7 @@ def request(self, method, url, body, headers, content_type=None):
197198
pybody = json.loads(body)
198199
except ValueError:
199200
pybody = body
200-
fancylogger.getLogger().debug('reponse len: %s ', len(pybody))
201+
logging.debug('reponse len: %s ', len(pybody))
201202
conn.close()
202203
return status, pybody
203204

@@ -241,13 +242,13 @@ def get_connection(self, method, url, body, headers):
241242
sep = '/'
242243
else:
243244
sep = ''
244-
if body:
245+
if body is not None:
245246
body = body.encode()
246247
request = Request(self.url + sep + url, data=body)
247248
for header, value in headers.items():
248249
request.add_header(header, value)
249250
request.get_method = lambda: method
250-
fancylogger.getLogger().debug('opening request: %s%s%s', self.url, sep, url)
251+
logging.debug('opening request: %s%s%s', self.url, sep, url)
251252
connection = self.opener.open(request)
252253
return connection
253254

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
from vsc.install.shared_setup import ag, kh, jt, sdw
3838

3939
PACKAGE = {
40-
'version': '3.5.2',
40+
'version': '3.5.3',
4141
'author': [sdw, jt, ag, kh],
4242
'maintainer': [sdw, jt, ag, kh],
4343
'install_requires': [

0 commit comments

Comments
 (0)