jetforce/examples/guestbook.py

64 lines
1.8 KiB
Python
Raw 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
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
DB = "/tmp/guestbook.sqlite"
2020-05-18 07:40:09 +02:00
SCHEMA = """
CREATE TABLE IF NOT EXISTS guestbook (
ip_address TEXT,
created_at timestamp,
message TEXT
)
"""
with sqlite3.connect(DB) as c:
c.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"]
with sqlite3.connect(DB, detect_types=sqlite3.PARSE_DECLTYPES) as c:
for row in c.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)
2020-05-18 07:40:09 +02:00
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"]
with sqlite3.connect(DB) as c:
values = (ip_address, created, message)
c.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()