Make API client a standalone script

This commit is contained in:
Théophile Bastian 2017-10-16 17:04:51 +02:00
parent 865a249002
commit 87071ef526

View file

@ -4,7 +4,10 @@ import json
import urllib.request import urllib.request
import hmac import hmac
import hashlib import hashlib
from datetime import datetime from datetime import datetime, date
import argparse
import os.path
import sys
def sendReq(url): def sendReq(url):
@ -59,3 +62,81 @@ def publish(bocId, url, date):
'url': url, 'url': url,
'date': date.strftime('%Y-%m-%d'), '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()