gaybook/app.py

90 lines
2.7 KiB
Python
Raw Normal View History

2023-06-01 09:48:52 +00:00
import flask
import dataclasses
import sqlite3
import datetime
import hashlib
app = flask.Flask(__name__)
def get_database_connection():
database_connection = sqlite3.connect("database/data.sqlite")
database_connection.row_factory = sqlite3.Row
return database_connection
@dataclasses.dataclass
class Quote:
author: str
content: str
timestamp: datetime.datetime = datetime.datetime.now()
def proof_of_work_is_valid(self, work: str):
to_hash = f"{self.author}\0{self.content}\0{work}"
hashed = hashlib.sha1(to_hash.encode("utf-8")).hexdigest()
return hashed[:5] == "00000"
def get_all_quotes() -> list[Quote]:
db_connection = get_database_connection()
db_quotes = db_connection.execute(
"SELECT author, content, timestamp FROM quotes ORDER BY timestamp DESC"
).fetchall()
db_connection.close()
quotes: list[Quote] = []
for db_quote in db_quotes:
quotes.append(Quote(db_quote["author"], db_quote["content"], db_quote["timestamp"]))
return quotes
def add_quote(new_quote: Quote) -> bool:
db_connection = get_database_connection()
matching_quote = db_connection.execute(
"SELECT author, content, timestamp FROM quotes WHERE author = ? AND content = ?",
(new_quote.author, new_quote.content)
).fetchall()
if matching_quote:
# There is already an author and a quote with the same content, let's not do duplicates...
return False
db_connection.execute(
2023-06-01 09:48:52 +00:00
"INSERT INTO quotes (author, content) VALUES (?, ?)",
(new_quote.author, new_quote.content)
)
db_connection.commit()
db_connection.close()
return True
2023-06-01 09:48:52 +00:00
@app.route('/', methods=["POST", "GET"])
def index():
message: str = ""
response_code = 200
if flask.request.method == "POST":
form = flask.request.form
if "username" not in form or "message" not in form or "proof-of-work" not in form:
message = "Did not provide username, quote or proof of work."
response_code = 400
else:
quote = Quote(form["username"], form["message"])
if quote.proof_of_work_is_valid(form["proof-of-work"]):
if add_quote(Quote(form["username"], form["message"])):
message = "Your quote was added successfully"
else:
message = "Couldn't add your quote. Is it a duplicate?"
response_code = 400
2023-06-01 09:48:52 +00:00
else:
message = "You didn't do the work, silly!"
response_code = 400
return flask.render_template("index.html", quotes=get_all_quotes(), message=message), response_code
if __name__ == "__main__":
app.run()