Skip to content
Snippets Groups Projects
alphaplan_fwr_import.py 2.38 KiB
Newer Older
#!/usr/bin/env python3
import argparse
import glob
import json
import sys

import requests


def ap_send_json(jsonobj: dict, url: str, user: str, password: str, cert_file: str):
    """Sends the generated files to the Alphaplan webservice"""
    try:
        msg = requests.post(
            url, json=jsonobj, auth=(user, password), verify=cert_file, timeout=10
        )
    except requests.exceptions.RequestException as e:

    try:
        msg_json = msg.json()
    except json.decoder.JSONDecodeError:
        sys.exit("ERROR: Did not receive a valid JSON reply from Alphaplan webservice")

    if msg_json["Status"] != "Ok":
        sys.exit("ERROR: AlphaPlan webservice post request failed")
    print(f'AlphaPlan webservice response: {msg_json["Meldung"]}')


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--file",
        help="""JSON file for Alphaplan FWR import""",
        dest="file",
        required=True,
    )
    parser.add_argument(
        "--url",
        help="""URL to the Alphaplan webservice""",
        dest="url",
        required=True,
    )
    parser.add_argument(
        "--user",
        help="""User for the Alphaplan webservice""",
        dest="user",
        required=True,
    )
    parser.add_argument(
        "--password",
        help="""Password for the Alphaplan webservice""",
        dest="password",
        required=True,
    )
    parser.add_argument(
        "--cert-file",
        help="""Certificate file for the Alphaplan webservice""",
        dest="cert_file",
        required=True,
    )
    args, _ = parser.parse_known_args()

    files = glob.glob(args.file, recursive=True)
    if not files:
        sys.exit(f"ERROR: no file(s) matching '{args.file}' found")
    print(f"Sending data to Alphaplan FWR webservice at {args.url}")

    # Get files from passed glob
    for filename in files:
        print(f"Importing JSON file {filename}")
        with open(filename, "r", encoding="utf-8") as f:
            try:
                json_data = json.load(f)
            except json.decoder.JSONDecodeError:
                sys.exit(f"ERROR: Could not parse JSON data from {filename}")
                args.url,
                args.user,
                args.password,
                args.cert_file,
            )


if __name__ == "__main__":
    main()