Python Forum
Responding correctly to HTTP request
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Responding correctly to HTTP request
#1
Question 
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!
Reply


Messages In This Thread
Responding correctly to HTTP request - by Calab - Apr-04-2023, 07:03 PM
RE: Responding correctly to HTTP request - by Calab - Apr-14-2023, 04:11 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to send unicode string encoded in utf-8 in http request in Python MaverinCode 1 32,648 Nov-08-2020, 06:45 AM
Last Post: JaiM
  Syntax error for HTTP request GET THX1138 1 6,429 May-12-2018, 12:02 PM
Last Post: snippsat
  HTTP Header request, how to improve efficiency andreamoro 5 5,223 May-01-2017, 03:49 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020