Python Forum

Full Version: Responding correctly to HTTP request
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?

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!
The problem here is that you use CGI,it has been dead💀 in Python for many years.
CGI is deprecated since version 3.11,and will be removed in version 3.13.

The common way to this in Python these day is to use eg Flask, FastAPI, or Django.
So WSGI is the replacement that is written all in Python.
All Framework today is written on top of WSGI(you don't use WSGI alone if not want to build new Framework).
(Apr-05-2023, 02:06 PM)snippsat Wrote: [ -> ]The problem here is that you use CGI,it has been dead💀 in Python for many years.
CGI is deprecated since version 3.11,and will be removed in version 3.13.

The common way to this in Python these day is to use eg Flask, FastAPI, or Django.
So WSGI is the replacement that is written all in Python.
All Framework today is written on top of WSGI(you don't use WSGI alone if not want to build new Framework).

Thanks! I will look into installing FastAPI onto our machine and work from there. I will also install Python 3.11 while I'm at it.