1+ # -*- coding: utf-8 -*-
2+ import argparse
3+ import urllib .request
4+ import json
5+ import sys
6+ import os
7+ import http .cookiejar
8+
9+
10+ def request (base_url , endpoint , method = "GET" , data = None , timeout = 5 , disable_cookies = False ):
11+ """
12+ Perform a raw API request (GET/POST), optionally without sending cookies.
13+ :param base_url: The base URL of the server.
14+ :param endpoint: API endpoint (e.g., "/api/compiler/<ID>/compile").
15+ :param method: HTTP method ("GET" or "POST").
16+ :param data: Data to send in a POST request (dict or None).
17+ :param timeout: Timeout duration for the request (in seconds).
18+ :param disable_cookies: If True, disables sending cookies.
19+ :return: Parsed JSON response if successful, None otherwise.
20+ """
21+ url = f"{ base_url } { endpoint } "
22+ headers = {
23+ "Content-Type" : "application/json" ,
24+ "Accept" : "application/json"
25+ }
26+
27+ try :
28+ json_data = json .dumps (data ).encode ("utf-8" ) if data else None
29+ req = urllib .request .Request (url , data = json_data , method = method , headers = headers )
30+
31+ if disable_cookies :
32+ opener = urllib .request .build_opener ()
33+ else :
34+ cookiejar = http .cookiejar .CookieJar ()
35+ opener = urllib .request .build_opener (urllib .request .HTTPCookieProcessor (cookiejar ))
36+
37+ with opener .open (req , timeout = timeout ) as response :
38+ raw_response = response .read ().decode ("utf-8" ).strip ()
39+
40+ if not raw_response :
41+ print ("[ERROR] Empty response received." , file = sys .stderr , flush = True )
42+ return None
43+
44+ return json .loads (raw_response )
45+
46+ except Exception as e :
47+ print (f"[ERROR] Exception thrown during { method } request to { endpoint } : { e } " , file = sys .stderr , flush = True )
48+ return None
49+
50+
51+ def load_json_file (json_path ):
52+ """
53+ Load a JSON payload from a file.
54+ :param json_path: Path to the JSON file.
55+ :return: Parsed JSON dictionary.
56+ """
57+ if not os .path .exists (json_path ):
58+ print (f"[ERROR] JSON file not found: { json_path } " , file = sys .stderr , flush = True )
59+ sys .exit (- 1 )
60+
61+ try :
62+ with open (json_path , "r" , encoding = "utf-8" ) as file :
63+ return json .load (file )
64+ except json .JSONDecodeError as e :
65+ print (f"[ERROR] Failed to parse JSON file: { e } " , file = sys .stderr , flush = True )
66+ sys .exit (- 1 )
67+
68+
69+ if __name__ == "__main__" :
70+ parser = argparse .ArgumentParser (description = "Raw API requester for Compiler Explorer." )
71+ parser .add_argument (
72+ "--url" ,
73+ type = str ,
74+ default = "http://localhost:80" ,
75+ help = "Base URL of the Compiler Explorer instance (default: http://localhost:80)."
76+ )
77+ parser .add_argument (
78+ "--endpoint" ,
79+ type = str ,
80+ required = True ,
81+ help = "API endpoint to query (e.g., /api/compiler/nsc_debug_upstream/compile)."
82+ )
83+ parser .add_argument (
84+ "--method" ,
85+ type = str ,
86+ choices = ["GET" , "POST" ],
87+ default = "GET" ,
88+ help = "HTTP method to use (GET or POST). Default is GET."
89+ )
90+ parser .add_argument (
91+ "--data" ,
92+ type = str ,
93+ default = None ,
94+ help = "JSON data for POST requests (as a string)."
95+ )
96+ parser .add_argument (
97+ "--json" ,
98+ type = str ,
99+ default = None ,
100+ help = "Path to a JSON file for POST request payload."
101+ )
102+ parser .add_argument (
103+ "--timeout" ,
104+ type = int ,
105+ default = 5 ,
106+ help = "Request timeout in seconds (default: 5)."
107+ )
108+ parser .add_argument (
109+ "--disable-cookies" ,
110+ action = "store_true" ,
111+ help = "Disable sending cookies with the request."
112+ )
113+
114+ args = parser .parse_args ()
115+
116+ if args .json :
117+ json_data = load_json_file (args .json )
118+ else :
119+ json_data = json .loads (args .data ) if args .data else None
120+
121+ result = request (args .url , args .endpoint , args .method , json_data , args .timeout , args .disable_cookies )
122+
123+ if result :
124+ print (json .dumps (result , indent = 2 ))
125+ sys .exit (0 )
126+ else :
127+ print ("[ERROR] Request failed." , file = sys .stderr , flush = True )
128+ sys .exit (- 1 )
0 commit comments