This repository has been archived on 2023-10-10. You can view files and clone it, but cannot push or open issues or pull requests.
paste/paste/home.py

98 lines
2.5 KiB
Python
Raw Normal View History

2023-09-25 13:30:27 +00:00
"""Manage view and create paste."""
2023-09-25 14:12:36 +00:00
from flask import (
Blueprint,
abort,
2023-09-25 14:12:36 +00:00
flash,
redirect,
render_template,
request,
url_for,
2023-09-25 14:12:36 +00:00
)
from werkzeug import Response
2023-09-25 13:30:27 +00:00
from paste.db import check_content_exist, connect_redis, insert_content_db
from paste.utils import generate_id, generate_secret, get_expiration_time
2023-09-25 13:30:27 +00:00
home = Blueprint("home", __name__, url_prefix="/")
def create_paste(content: str, time: int) -> dict[str, str]:
2023-09-25 13:30:27 +00:00
"""
Create paste in DB.
:param time: Expiration time in second
2023-09-25 13:30:27 +00:00
:param content: Content to add in redis.
:return: A dict with url_id and delete secret.
2023-09-25 13:30:27 +00:00
"""
secret = generate_secret()
2023-09-25 13:30:27 +00:00
url_id = generate_id()
while check_content_exist(url_id):
url_id = generate_id()
insert_content_db(url_id, time, content, secret)
return {"url_id": url_id, "secret": secret}
2023-09-25 13:30:27 +00:00
@home.route("/")
def homepage() -> str:
"""
Homepage.
:return: Homepage.
"""
return render_template("home.html.j2")
@home.route("/create", methods=["POST"])
2023-09-25 14:12:36 +00:00
def create() -> Response:
2023-09-25 13:30:27 +00:00
"""
Receive POST data for create paste.
:return: Redirection to homapage.
"""
content = request.form.get("content")
2023-09-26 09:32:42 +00:00
time = request.form.get("time")
time = 0 if time == "" else int(time)
2023-09-26 09:32:42 +00:00
flash_data = create_paste(content, time)
flash(flash_data["url_id"], category="create")
flash(flash_data["secret"], category="create")
2023-09-25 13:30:27 +00:00
return redirect(url_for("home.homepage"))
@home.route("/delete/<path:path>")
def delete_paste(path: str) -> Response:
"""
Delete a paste
:param path: path fetched from url
:return: forbidden (403) or homepage.
"""
db = connect_redis()
secret = request.args.get("secret")
if db.hget(path, "secret") == secret:
db.delete(path)
flash(path, category="delete")
return redirect(url_for("home.homepage"))
return abort(403)
2023-09-25 13:30:27 +00:00
@home.route("/<path:path>")
def get_content(path: str) -> Response | str:
2023-09-25 13:30:27 +00:00
"""
Return paste for asked url.
:param path: Requested path.
:return: Paste content.
"""
db = connect_redis()
data = db.hgetall(path)
if check_content_exist(path):
flash(data["content"])
cache_time = get_expiration_time(path)
current_response = Response(render_template("content.html.j2"))
if cache_time == -1:
current_response.headers["Cache-Control"] = "public"
else:
current_response.headers["Cache-Control"] = f"public, {cache_time}"
return current_response
return abort(404)