Skip to content

Instantly share code, notes, and snippets.

@remysucre
Created January 19, 2024 00:17
Show Gist options
  • Save remysucre/ecc0ace21be34141a6a9c807943eea0d to your computer and use it in GitHub Desktop.
Save remysucre/ecc0ace21be34141a6a9c807943eea0d to your computer and use it in GitHub Desktop.
CGI script in Python for a guestbook
#!/usr/bin/env python
import cgi
import sqlite3
# Create or connect to the SQLite database
conn = sqlite3.connect('gb.db')
cursor = conn.cursor()
# Create a table to store guestbook entries if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message TEXT
)
''')
# Function to fetch and display guestbook entries
def display_guestbook_entries():
cursor.execute('SELECT * FROM entries ORDER BY id DESC')
entries = cursor.fetchall()
print("<h2>Guestbook Entries:</h2>")
print("<ul>")
for entry in entries:
print(f"<li>{entry[1]}</li>")
print("</ul>")
# Handle form submission
form = cgi.FieldStorage()
if "message" in form:
message = form["message"].value
# Insert user input into the database
cursor.execute("INSERT INTO entries (message) VALUES (?)", (message,))
conn.commit()
# Print the HTML content
print("Content-type: text/html\n")
print("<html>")
print("<head>")
print("<title>Guestbook</title>")
print("</head>")
print("<body>")
print("<h1>Guestbook</h1>")
print("<form method='post' action='gb.cgi'>")
print("<label for='message'>Leave a message:</label>")
print("<input type='text' name='message' id='message' required>")
print("<input type='submit' value='Submit'>")
print("</form>")
display_guestbook_entries()
print("</body>")
print("</html>")
# Close the database connection
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment