75 lines
2.2 KiB
Python
75 lines
2.2 KiB
Python
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):
|
|
db_connexion = get_database_connection()
|
|
db_connexion.execute(
|
|
"INSERT INTO quotes (author, content) VALUES (?, ?)",
|
|
(new_quote.author, new_quote.content)
|
|
)
|
|
db_connexion.commit()
|
|
db_connexion.close()
|
|
|
|
|
|
@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"]):
|
|
add_quote(Quote(form["username"], form["message"]))
|
|
message = "Your quote was added successfully"
|
|
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()
|