jetforce/examples/guestbook.py

60 lines
1.6 KiB
Python
Raw Permalink Normal View History

"""
2020-05-18 07:40:09 +02:00
A simple guestbook application that accepts and displays text messages.
This is an example of how to return a 10 INPUT request to the client and
2020-05-19 05:52:34 +02:00
retrieve their response by parsing the URL query string.
This example stores the guestbook inside of a persistent sqlite database.
"""
2020-05-18 07:40:09 +02:00
import sqlite3
from datetime import datetime
2020-05-18 07:40:09 +02:00
from jetforce import GeminiServer, JetforceApplication, Response, Status
2020-05-26 06:25:48 +02:00
db = sqlite3.connect("/tmp/guestbook.sqlite", detect_types=sqlite3.PARSE_DECLTYPES)
2020-05-18 07:40:09 +02:00
SCHEMA = """
CREATE TABLE IF NOT EXISTS guestbook (
ip_address TEXT,
created_at timestamp,
message TEXT
)
"""
2020-05-26 06:25:48 +02:00
db.execute(SCHEMA)
2020-05-18 07:40:09 +02:00
app = JetforceApplication()
@app.route("", strict_trailing_slash=False)
2019-08-23 00:53:02 +02:00
def index(request):
2020-05-18 07:40:09 +02:00
lines = ["Guestbook", "=>/submit Sign the Guestbook"]
2020-05-26 06:25:48 +02:00
for row in db.execute("SELECT * FROM guestbook ORDER BY created_at"):
ip_address, created_at, message = row
line = f"{created_at:%Y-%m-%d} - [{ip_address}] {message}"
lines.append("")
lines.append(line)
2020-05-18 07:40:09 +02:00
lines.extend(["", "...", ""])
body = "\n".join(lines)
return Response(Status.SUCCESS, "text/gemini", body)
2019-08-23 00:53:02 +02:00
@app.route("/submit")
def submit(request):
if request.query:
message = request.query[:256]
2020-05-18 07:40:09 +02:00
created = datetime.now()
ip_address = request.environ["REMOTE_HOST"]
2020-05-26 06:25:48 +02:00
values = (ip_address, created, message)
db.execute("INSERT INTO guestbook VALUES (?, ?, ?)", values)
2019-08-23 00:53:02 +02:00
return Response(Status.REDIRECT_TEMPORARY, "")
else:
return Response(Status.INPUT, "Enter your message (max 256 characters)")
if __name__ == "__main__":
2020-05-18 07:40:09 +02:00
server = GeminiServer(app)
server.run()