From 87071ef526ff822c3c39fa23eebc69c35c5985a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9ophile=20Bastian?= Date: Mon, 16 Oct 2017 17:04:51 +0200 Subject: [PATCH] Make API client a standalone script --- api/client/apiclient.py | 83 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/api/client/apiclient.py b/api/client/apiclient.py index 018a430..526795e 100644 --- a/api/client/apiclient.py +++ b/api/client/apiclient.py @@ -4,7 +4,10 @@ import json import urllib.request import hmac import hashlib -from datetime import datetime +from datetime import datetime, date +import argparse +import os.path +import sys def sendReq(url): @@ -59,3 +62,81 @@ def publish(bocId, url, date): 'url': url, 'date': date.strftime('%Y-%m-%d'), } + + +############################################################################### + +TOKEN_DFT_FILE = os.path.expanduser("~/.bocal_api_token") +DFT_HOST = 'bocal.cof.ens.fr' + + +def read_token(path): + token = '' + try: + with open(path, 'r') as handle: + token = handle.readline().strip() + except FileNotFoundError: + print("[Erreur] Fichier d'identifiants absent (`{}`).".format(path), + file=sys.stderr) + sys.exit(1) + return token + + +def cmd(func): + def wrap(parse_args, *args, **kwargs): + token = read_token(parse_args.creds) + return func(token, parse_args, *args, **kwargs) + return wrap + + +@cmd +def cmd_publish(token, args): + publish_date = date.today() if not args.date else args.date + (ret_code, ret_str) = publish(args.host, + token, + args.numero, + args.url, + publish_date) + if ret_code == 200: + print("Succès :)") + else: + print("[Erreur :c] {} : {}".format(ret_code, ret_str)) + sys.exit(1) + + +def setup_argparse(): + parser = argparse.ArgumentParser() + parser.add_argument('--host', + help=("Adresse du site à contacter (par défaut, " + "`{}`).".format(DFT_HOST))) + parser.add_argument('--creds', + help=("Fichier contenant le token API à utiliser " + "(par défaut, `{}`)".format(TOKEN_DFT_FILE))) + parser.set_defaults(creds=TOKEN_DFT_FILE) + subparsers = parser.add_subparsers() + + parser_publish = subparsers.add_parser('publier', + help='Publier un numéro du BOcal') + parser_publish.add_argument('numero', + help='Numéro du BOcal') + parser_publish.add_argument('url', + help='Adresse (locale) du PDF du BOcal') + parser_publish.add_argument('-d', '--date', + help="Date de publication indiquée") + parser_publish.set_defaults(func=cmd_publish) + + out_args = parser.parse_args() + if 'func' not in out_args: # No subcommand provided + print("You must provide a command.", file=sys.stderr) + print(parser.parse_args(['-h']), file=sys.stderr) + sys.exit(1) + return out_args + + +def main(): + args = setup_argparse() + args.func(args) + + +if __name__ == '__main__': + main()