guestbook/app.py
2024-09-19 20:47:19 +03:00

55 lines
1.9 KiB
Python

import hashlib, os
import time
from flask import Flask, redirect, render_template, request
import sqlite3
import re
app = Flask(__name__)
db = sqlite3.connect('guestbook.db', check_same_thread=False)
cs = db.cursor()
app.secret_key = hashlib.md5(os.urandom(32)).hexdigest()
@app.template_filter('parsetime')
def parsetime(value):
return time.strftime('%Y-%m-%d %H:%M', time.localtime(value))
@app.route('/')
def index():
statement = 'SELECT "id", "name", "website", "comment", "date", "ip" FROM "entries" ORDER BY id DESC'
cs.execute(statement)
comments = cs.fetchall()
statement = 'SELECT DISTINCT website FROM entries'
cs.execute(statement)
sites = cs.fetchall()
print(sites)
return render_template("index.html", comments=comments, sites=sites)
@app.route('/submit', methods=["POST"])
def submit():
errors = []
name = request.form.get("name")
website = request.form.get("website")
comment = request.form.get("comment")
if name != "":
if name.isalnum() != True:
errors.append("Your name must not contain any non-alphanumeric characters")
else:
name = "Anonymous"
if website !="":
if not re.fullmatch(r"^[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*\.[a-zA-Z]{2,3}(\.[a-zA-Z]{2,3})?$", website):
errors.append("Your site doesn't look valid.")
if comment == "":
errors.append("You must write something.")
elif len(comment) > 512:
errors.append("You wrote more than 512 characters")
if errors != []:
response = ""
for error in errors:
response += f"{error}<br>"
return response
statement = 'INSERT INTO "entries" ("name", "website", "comment", "date", "ip") VALUES (?, ?, ?, ?, ?);'
values = (name, website, comment, int(time.time()), str(request.remote_addr))
cs.execute(statement, values)
db.commit()
#change this if you run it on anything other than /gb
return redirect("/gb")