Problem Statement: Create a basic CGI script in Python that allows students to submit their name and grade through a form and displays a personalized message based on their input?
Prerequisites
- Ensure you have a web server capable of running CGI scripts (e.g., Apache or Python's built-in HTTP server with CGI enabled).
- Save the script in a directory configured for CGI execution (e.g.,
cgi-bin
).
Save this script as student_form.py
in your CGI directory.
import cgi
import cgitb
# Enable debugging
cgitb.enable()
def main ():
# Output HTTP headers
print ("Content-Type: text/html\n")
# Get form data
form = cgi.FieldStorage()
name = form.getvalue("name", ""). strip()
grade = form.getvalue("grade", ""). strip ()
# HTML Response
print ("""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Grade Submission</title>
</head>
<body>
""")
if not name or not grade:
print ("""
<h1>Student Grade Submission</h1>
<form method="post" action="student_form.py">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br><br>
<label for="grade">Grade:</label><br>
<input type="text" id="grade" name="grade" required><br><br>
<button type="submit">Submit</button>
</form>
""")
else:
# Generate personalized message
try:
grade = float(grade)
if grade >= 90:
message = "Excellent work!"
elif grade >= 75:
message = "Good job, keep improving!"
elif grade >= 50:
message = "You passed, but there's room for improvement."
else:
message = "Unfortunately, you did not pass. Better luck next time!"
except ValueError:
message = "Invalid grade input. Please enter a numeric grade."
print (f"""
<h1>Hello, {name}! </h1>
<p>Your grade is: {grade}</p>
<p>{message}</p>
<a href="student_form.py">Submit another grade</a>
""")
print ("""
</body>
</html>
""")
if __name__ == "__main__":
main ()
No comments:
Post a Comment