utiliser des uri et non des messages depuis le client

This commit is contained in:
Emmanuel Garette 2020-09-02 09:03:18 +02:00
parent 39206076f1
commit ee37254fa6
5 changed files with 38 additions and 41 deletions

View File

@ -10,13 +10,15 @@ from cucchiaiata.i18n import _
def main(): def main():
try: try:
if len(argv) > 2 and argv[1] in ['setting.session.server.configure', if len(argv) > 2 and argv[1] in ['v1.setting.session.server.configure',
'setting.session.servermodel.configure']: 'v1.setting.session.servermodel.configure']:
Configuration().get() Configuration().get()
else: else:
parser = Parser() parser = Parser()
print(dumps(parser.get(), print(dumps(parser.get(),
indent=config.indent)) indent=config.indent))
except KeyboardInterrupt:
pass
except Exception as err: except Exception as err:
if config.debug: if config.debug:
print_exc() print_exc()
@ -25,7 +27,4 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
try: main()
main()
except KeyboardInterrupt:
pass

View File

@ -32,16 +32,16 @@ class Common:
return err return err
def remote_json_to_config(self, def remote_json_to_config(self,
url=None, url,
config_type=Config): config_type=Config,
):
"retrieves the remote config from the distant api description" "retrieves the remote config from the distant api description"
if url is None:
url = self.cucchiaiata_config.remote_url
token = self.get_token() token = self.get_token()
headers = {'Authorization':'Bearer {}'.format(token)} headers = {'Authorization':'Bearer {}'.format(token)}
req = get(url, req = get(url,
headers=headers, headers=headers,
verify=config.allow_insecure_https) verify=config.allow_insecure_https,
)
code = req.status_code code = req.status_code
if code != 200: if code != 200:
raise Exception(self.get_error_from_http(req)) raise Exception(self.get_error_from_http(req))
@ -49,9 +49,14 @@ class Common:
return config_type(json) return config_type(json)
def send_data(message: str, def send_data(uri: str,
payload: Dict): payload: Dict,
final_url = '{}/{}'.format(config.remote_url, message) ):
version, message = uri.split('.', 1)
final_url = '{}/{}/{}'.format(config.remote_url,
version,
message,
)
ret = post(final_url, ret = post(final_url,
data=dumps(payload), data=dumps(payload),
verify=config.allow_insecure_https) verify=config.allow_insecure_https)

View File

@ -11,11 +11,7 @@ class Config:
if not isfile(config_file): if not isfile(config_file):
print(_('Attention, there is no configuration file')) print(_('Attention, there is no configuration file'))
url = input(_('Address to Risotto server: ')) url = input(_('Address to Risotto server: '))
version = input(_('Risotto API\'s version (default: "v1"): ')) yaml_template = f'url: {url}'
if not version:
version = "v1"
yaml_template = f"""url: {url}
version: {version}"""
with open(config_file, 'w') as fh: with open(config_file, 'w') as fh:
fh.write(yaml_template) fh.write(yaml_template)
@ -28,9 +24,8 @@ version: {version}"""
raise Exception(_('Error when creating the config file {}').format(err)) raise Exception(_('Error when creating the config file {}').format(err))
self.url = config['url'] self.url = config['url']
self.version = config['version']
self.debug = config.get('debug', False) self.debug = config.get('debug', False)
self.remote_url = 'http://{}/api/{}'.format(self.url, self.version) self.remote_url = f'http://{self.url}/api'
self.token_file = join(expanduser("~"), '.zephir-client.jwt.token') self.token_file = join(expanduser("~"), '.zephir-client.jwt.token')
self.indent = config.get('indent', 2) self.indent = config.get('indent', 2)
self.allow_insecure_https = config.get('allow_insecure_https', False) self.allow_insecure_https = config.get('allow_insecure_https', False)

View File

@ -3,16 +3,16 @@ from sys import argv, exit
from tiramisu_cmdline_parser import TiramisuCmdlineParser from tiramisu_cmdline_parser import TiramisuCmdlineParser
from tiramisu_api import Config from tiramisu_api import Config
from cucchiaiata.i18n import _
from .i18n import _
from .parser import Parser
from .common import send_data, Common from .common import send_data, Common
class ConfigAPI(Config): class ConfigAPI(Config):
def send_data(self, def send_data(self,
data): data):
for index, payload in enumerate(data['updates']): for index, payload in enumerate(data['updates']):
payload['session_id'] = self.session_id payload['session_id'] = self.session_id
if isinstance(payload['value'], list): if isinstance(payload['value'], list):
payload['value_multi'] = payload['value'] payload['value_multi'] = payload['value']
@ -25,15 +25,16 @@ class ConfigAPI(Config):
class Configuration(Common): class Configuration(Common):
def configure_server(self): def configure_server(self):
if self.message == 'setting.session.server.configure': smessage = self.message.split('.')
type = 'server' version = smessage[0]
else: type = smessage[-2]
type = 'servermodel' url = '{}/{}/setting/{}/{}'.format(self.cucchiaiata_config.remote_url,
url = '{}/setting/{}/{}'.format(self.cucchiaiata_config.remote_url, version,
type, type,
self.session_id) self.session_id)
tconfig = self.remote_json_to_config(url, tconfig = self.remote_json_to_config(url,
ConfigAPI) ConfigAPI,
)
tconfig.message = self.message tconfig.message = self.message
tconfig.session_id = self.session_id tconfig.session_id = self.session_id
return tconfig return tconfig
@ -52,14 +53,9 @@ class Configuration(Common):
index = parameters.index('-s') index = parameters.index('-s')
except ValueError: except ValueError:
try: try:
index = parameters.index('--sessionid') index = parameters.index('--session_id')
except ValueError: except ValueError:
# FIXME not working ... parser = Parser()
tiramisu_config = self.remote_json_to_config(ConfigAPI)
parser = TiramisuCmdlineParser(tiramisu_config,
self.prog,
unrestraint=True,
fullpath=True)
parser.print_help() parser.print_help()
exit(1) exit(1)
parameters.pop(index) parameters.pop(index)

View File

@ -19,12 +19,14 @@ class Parser(Common):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
# build a tiramisu parser and parse argument # build a tiramisu parser and parse argument
self.remote_config = self.remote_json_to_config() url = self.cucchiaiata_config.remote_url
self.remote_config = self.remote_json_to_config(url)
parser = CucchiaiataParser(self.remote_config, parser = CucchiaiataParser(self.remote_config,
fullpath=False, fullpath=False,
remove_empty_od=True, remove_empty_od=True,
display_modified_value=False, display_modified_value=False,
formatter_class=RawDescriptionHelpFormatter) formatter_class=RawDescriptionHelpFormatter,
)
parser.parse_args() parser.parse_args()
def get(self): def get(self):