Saving the forms contents

When we have a message, we need to save the message to the database. To do this, we'll need to parse the value we read from the form and then use a sqlite3 query to store it in the database. To make this easier, we've added a helper function to parse the form string into a dictionary, and we've added the current timestamp to that dictionary. Then, the dictionary is used as the parameter for a SQL query to save the message to the database (see listing 24.3).

Listing 24.3 File message_wall03.py from wsgiref.simple_server import make_server from io import StringlO import sqlite3 import datetime def get_form_vals(post_str):

form_vals = {item.split("=")[0]: item.split("=")[1] for item in post_str.decode().split("&")} return form_vals def message_wall_app(environ, start_response): output = StringIO() status = b'200 OK' # HTTP Status headers = [(b'Content-type', b'text/html; charset=utf-8')] start_response(status, headers) print("<h1>Message Wall</h1>", file=output) if environ['REQUEST_METHOD'] == 'POST':

size = int(environ['CONTENT_LENGTH']) post_str = environ['wsgi.input'].read(size) form_vals = get_form_vals(post_str) form_vals['timestamp'] = datetime.datetime.now() print(form_vals, "<p>", file=output)

cursor.execute("insert into messages (user, message, ts) values " "(:user, :message, :timestamp)", form_vals) print('<form method="POST">User: <input type="text" ' 'name="user">Message: <input type="text" '

'name="message"><input type="submit" value="Send"></form>', file=output) return [output.getvalue()]

httpd = make_server('', 8000, message_wall_app) print("Serving on port 8000...")

conn = sqlite3.connect("messagefile") cursor = conn.cursor() httpd.serve_forever()

We use a dictionary comprehension to transform post_str into a dictionary O. Then, we add a timestamp to the form_vals dictionary ©. Sqlite3 connection and cursor objects are created only once for an application ©.

Was this article helpful?

0 0

Post a comment