listing26-8.py 984 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #!/usr/bin/python
  2. print('Content-type: text/html\n')
  3. import cgitb; cgitb.enable()
  4. import psycopg2
  5. conn = psycopg2.connect('user=foo password=bar dbname=baz')
  6. curs = conn.cursor()
  7. import cgi, sys
  8. form = cgi.FieldStorage()
  9. sender = form.getvalue('sender')
  10. subject = form.getvalue('subject')
  11. text = form.getvalue('text')
  12. reply_to = form.getvalue('reply_to')
  13. if not (sender and subject and text):
  14. print('Please supply sender, subject, and text')
  15. sys.exit()
  16. if reply_to is not None:
  17. query = ("""
  18. INSERT INTO messages(reply_to, sender, subject, text)
  19. VALUES(%s, '%s', '%s', '%s')""", (int(reply_to), sender, subject, text))
  20. else:
  21. query = ("""
  22. INSERT INTO messages(sender, subject, text)
  23. VALUES('%s', '%s', '%s')""", (sender, subject, text))
  24. curs.execute(*query)
  25. conn.commit()
  26. print("""
  27. <html>
  28. <head>
  29. <title>Message Saved</title>
  30. </head>
  31. <body>
  32. <h1>Message Saved</h1>
  33. <hr />
  34. <a href='main.cgi'>Back to the main page</a>
  35. </body>
  36. </html>s
  37. """)