Skip to content

Commit 9dad80c

Browse files
committed
add custom api support
- Add custom API url - use f-strings for urls
1 parent b5fc7f0 commit 9dad80c

2 files changed

Lines changed: 23 additions & 8 deletions

File tree

coderunner/coderunner.py

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -57,15 +57,21 @@
5757
"useQueryString": True
5858
}
5959

60-
HOST_URL = "https://judge0.p.rapidapi.com/"
61-
API_URL = "https://judge0.p.rapidapi.com/submissions/"
60+
API_URL = "https://judge0.p.rapidapi.com/"
61+
#API_URL = "https://judge0.p.rapidapi.com/submissions/"
6262
FIELDS = "?fields=stdout,memory,time,status,stderr,exit_code,created_at"
6363

6464

6565
class ValueTooLargeError(Exception):
6666
"""Raised when the input value is too large"""
6767

6868

69+
class InvalidURL(Exception):
70+
"""Raise when api_url is invalid"""
71+
def __init__(self, message):
72+
super.__init__(message)
73+
74+
6975
class code:
7076
"""
7177
Args:
@@ -138,10 +144,10 @@ def __readStandardInput(self):
138144

139145
def __readStatus(self, token: str):
140146
"""
141-
Check Submission status
147+
Check Submission Status
142148
"""
143149
while True:
144-
req = urllib.request.Request(API_URL + token["token"] + FIELDS, headers=HEADERS)
150+
req = urllib.request.Request(f'{self.API_URL}submissions/{token["token"]}{FIELDS}', headers=HEADERS)
145151
with urllib.request.urlopen(req) as response:
146152
req = response.read()
147153

@@ -167,16 +173,25 @@ def __submit(self):
167173
api_params["source_code"] = self.source
168174

169175
post_data = urllib.parse.urlencode(api_params).encode("ascii")
170-
req = urllib.request.Request(API_URL, post_data, headers=HEADERS)
176+
req = urllib.request.Request(f'{API_URL}submissions/', post_data, headers=HEADERS)
171177
with urllib.request.urlopen(req) as response:
172178
req = response.read()
173179
token = json.loads(req.decode("utf-8"))
174180

175181
return token
176182

177-
def authenticate(self, key: str):
183+
def api(self, key: str, url: str = None):
184+
"""Setup API url and key"""
185+
HEADERS["x-rapidapi-key"] = key
178186
self.API_KEY = key
179-
HEADERS["x-rapidapi-key"] = self.API_KEY
187+
if url is None:
188+
self.API_URL = API_URL
189+
else:
190+
user_api_url = urllib.parse.urlparse(url)
191+
if user_api_url.scheme and user_api_url.netloc:
192+
self.API_URL = url
193+
else:
194+
raise InvalidURL("Invalid API URL")
180195

181196
def getSubmissionDate(self):
182197
"""Submission date/time of program"""

demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
API_KEY = os.environ["API_KEY"]
1515

1616
r = coderunner.code(source_code, language, output, Input)
17-
r.authenticate(API_KEY)
17+
r.api(key=API_KEY)
1818

1919
# r2 = coderunner.code("print(\"yo\")", "Python3", "YO", path=False)
2020

0 commit comments

Comments
 (0)