Skip to content

Commit dd0aa9f

Browse files
authored
Refactor GET and POST request handling in restapis.py
Refactor error handling and improve code comments.
1 parent 7f19a96 commit dd0aa9f

File tree

1 file changed

+21
-20
lines changed

1 file changed

+21
-20
lines changed

server/djangoapp/restapis.py

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,50 +3,51 @@
33
import os
44
from dotenv import load_dotenv
55

6+
# Load environment variables
67
load_dotenv()
78

8-
backend_url = os.getenv(
9-
'backend_url', default="http://localhost:3030")
9+
backend_url = os.getenv('backend_url', default="http://localhost:3030")
1010
sentiment_analyzer_url = os.getenv(
11-
'sentiment_analyzer_url',
12-
default="http://localhost:5050/")
11+
'sentiment_analyzer_url', default="http://localhost:5050/"
12+
)
1313

1414

15-
# Add code for get requests to back end
15+
# Add code for GET requests to backend
1616
def get_request(endpoint, **kwargs):
1717
params = ""
18-
if(kwargs):
19-
for key,value in kwargs.items():
20-
params=params+key+"="+value+"&"
18+
if kwargs:
19+
for key, value in kwargs.items():
20+
params = params + key + "=" + value + "&"
2121

22-
request_url = backend_url+endpoint+"?"+params
22+
request_url = backend_url + endpoint + "?" + params
23+
print(f"GET from {request_url}")
2324

24-
print("GET from {} ".format(request_url))
2525
try:
2626
# Call get method of requests library with URL and parameters
2727
response = requests.get(request_url)
2828
return response.json()
29-
except:
30-
# If any error occurs
31-
print("Network exception occurred")
29+
except Exception as err:
30+
# Handle network or JSON errors gracefully
31+
print(f"Network exception occurred: {err}")
32+
3233

3334
def analyze_review_sentiments(text):
34-
request_url = sentiment_analyzer_url+"analyze/"+text
35+
request_url = sentiment_analyzer_url + "analyze/" + text
3536
try:
36-
# Call get method of requests library with URL and parameters
3737
response = requests.get(request_url)
3838
print(response)
3939
return response.json()
4040
except Exception as err:
41-
print(f"Unexpected {err=}, {type(err)=}")
41+
print(f"Unexpected error: {err} ({type(err)})")
4242
print("Network exception occurred")
4343

44+
4445
# Add code for posting review
4546
def post_review(data_dict):
46-
request_url = backend_url+"/insert_review"
47+
request_url = backend_url + "/insert_review"
4748
try:
48-
response = requests.post(request_url,json=data_dict)
49+
response = requests.post(request_url, json=data_dict)
4950
print(response.json())
5051
return response.json()
51-
except:
52-
print("Network exception occurred")
52+
except Exception as err:
53+
print(f"Network exception occurred: {err}")

0 commit comments

Comments
 (0)