import code
import traceback
import json
import requests
import argparse
import art
# Parsing Arguments (URL of Prometheus instance running)
parser = argparse.ArgumentParser(description='Query PromQL via Interpreter')
parser.add_argument('--url', dest='URL', type=str, default='http://localhost:9090', 
                    help='Domain/IP of the Prometheus (default: http://localhost:9090)')
args = parser.parse_args()
args.URL = args.URL.rstrip('/')
# Printing Banner of the Session (URL of Prometheus instance running)
print(f'Connecting to {args.URL}/api/v1/query','\n')
art.tprint("PromQL Interpreter")
print('Enter Query to check, Enter Ctrl+Z to Exit')
# repl loop
def repl(query):
    while query:
        try:
            # getting PromQL Query as Input
            query = input('query > ')
        except EOFError as e:
            break
        try:
            # Making a Post request to the Prometheus End Point
            resp = requests.post(f"{args.URL}/api/v1/query", data={'query': query }, 
            headers={'Content-Type': 'application/x-www-form-urlencoded'})
            # Printing Response Code
            print(f"response code : {resp.status_code}")
            # Printing response Payload if response status code is 200 OK
            if resp.status_code == requests.codes.ok:
            	print(json.dumps(json.loads(resp.text), indent=2))
        except Exception as err:
            # Traceback of errors if any
            traceback.print_exc()
if __name__ == '__main__':
    inp = True
    repl(inp)
    Usage of the python file is shown below.
query command : promhttp_metric_handler_requests_total{code="200"}

