I have a Linux host that is running Apache. I am able to execute my Python 3 scripts on that host using a web request.
My problem is that I don't know the correct way to respond in my code. The code below is a simple example. I go to (link removed spam) and I would expect to get a status code of 200 and a JSON response of "Good age". Any age below 18 or above 50, or non-number should generate a status code of 400 and a different JSON response.
I'm sure that there is probably a site on the web that would explain this, but I'm having no luck with my searches.
What should I be doing to respond correctly to this web request?
My problem is that I don't know the correct way to respond in my code. The code below is a simple example. I go to (link removed spam) and I would expect to get a status code of 200 and a JSON response of "Good age". Any age below 18 or above 50, or non-number should generate a status code of 400 and a different JSON response.
I'm sure that there is probably a site on the web that would explain this, but I'm having no luck with my searches.
What should I be doing to respond correctly to this web request?
import cgi
import json
def safe_int(val, default=None):
try:
return int(val)
except (ValueError, TypeError):
return default
form = cgi.FieldStorage()
msg = None
if "age" in form.keys():
age = safe_int(form["age"].value)
else:
age = None
if age:
if age < 18:
msg = "Too young"
status_code = 400
status_reason = "Bad_value"
elif age > 50:
msg = "Too old"
status_code = 400
status_reason = "Bad value"
else:
msg = "Good age"
status_code = 200
status_reason = "OK"
else:
msg = "No age given"
status_code = 400
status_reason = "Bad value"
print(f"HTTP/1.1 {status_code} {status_reason}\r\n", end="")
print("Content-type: application/json\r\n\r\n", end="")
json_msg = json.dumps(msg)
print(json_msg)Thanks for any help!
