jetforce/examples/guestbook.py

61 lines
1.5 KiB
Python
Raw Normal View History

"""
2019-08-23 00:53:02 +02:00
A guestbook application that accepts input from guests and stores messages in
a simple text file.
"""
import asyncio
2019-08-23 00:53:02 +02:00
import pathlib
from datetime import datetime
import jetforce
2019-08-23 00:53:02 +02:00
from jetforce import Response, Status
2019-08-23 00:53:02 +02:00
guestbook = pathlib.Path("guestbook.txt")
2019-08-23 00:53:02 +02:00
app = jetforce.JetforceApplication()
@app.route("")
2019-08-23 00:53:02 +02:00
def index(request):
data = ["Guestbook", "=>/submit Sign the Guestbook", ""]
2019-08-23 00:53:02 +02:00
guestbook.touch(exist_ok=True)
with guestbook.open("r") as fp:
for line in fp:
line = line.strip()
if line.startswith("=>"):
data.append(line[2:])
else:
2019-08-23 00:53:02 +02:00
data.append(line)
2019-08-23 00:53:02 +02:00
data.extend(["", "...", ""])
return Response(Status.SUCCESS, "text/gemini", "\n".join(data))
2019-08-23 00:53:02 +02:00
@app.route("/submit")
def submit(request):
if request.query:
message = request.query[:256]
created = datetime.utcnow()
with guestbook.open("a") as fp:
fp.write(f"\n[{created:%Y-%m-%d %I:%M %p}]\n{message}\n")
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__":
2019-08-23 00:53:02 +02:00
args = jetforce.command_line_parser().parse_args()
ssl_context = jetforce.make_ssl_context(
args.hostname, args.certfile, args.keyfile, args.cafile, args.capath
)
server = jetforce.GeminiServer(
host=args.host,
port=args.port,
ssl_context=ssl_context,
hostname=args.hostname,
app=app,
)
asyncio.run(server.run())