fix: fresh file id
All checks were successful
ci/woodpecker/push/publish Pipeline was successful

This commit is contained in:
Mylloon 2023-12-22 03:29:59 +01:00
parent 8f0ae0d4f5
commit c8291f415b
Signed by: Anri
GPG key ID: A82D63DFF8D1317F
2 changed files with 42 additions and 18 deletions

View file

@ -1,8 +1,6 @@
from os import path as os_path
from config import Config from config import Config
from flask import Blueprint, flash, redirect, render_template, request from flask import Blueprint, flash, redirect, render_template, request
from utils.misc import get_posts, post_filename from utils.misc import create_post, fresh_file_id, get_posts
from werkzeug import Response from werkzeug import Response
name = __name__.split(".")[-1] name = __name__.split(".")[-1]
@ -26,23 +24,15 @@ def new_post() -> Response:
if Config.is_logged(): if Config.is_logged():
content = request.form.get("p") content = request.form.get("p")
if content: if content:
# finding all posts
paths = get_posts()
# finding an appropriate filename # finding an appropriate filename
filename = 0 filename = fresh_file_id()
if len(paths) > filename:
filename = paths.index(max(iter(paths), key=os_path.getmtime)) + 1
# creating the post # create/update the post
with open( update = create_post(filename, content)
post_filename(filename),
"w",
encoding="utf-8",
) as f:
f.write(content)
flash(f"<a href='/read/{filename}'>post created</a>.") flash(
f"<a href='/read/{filename}'>post {'updated' if update else 'created'}</a>."
)
else: else:
flash(f"invalid post: {content}") flash(f"invalid post: {content}")
else: else:

View file

@ -5,7 +5,7 @@ from os import remove as os_remove
from config import Config from config import Config
def post_filename(number: int): def post_filename(number: int) -> str:
"""get filename of post""" """get filename of post"""
return f"{Config.data_dir}/{number}.txt" return f"{Config.data_dir}/{number}.txt"
@ -37,3 +37,37 @@ def delete_post(filename: str) -> bool:
else: else:
os_remove(filename) os_remove(filename)
return True return True
def fresh_file_id() -> int:
# finding all posts
paths = get_posts()
# use the latest file as the reference and increment the ID
filename = 0
if len(paths) > filename:
chosen = max(iter(paths), key=os_path.getmtime)
# add 1 to the chosen id
filename = int(chosen.split("/")[-1][:-4]) + 1
return filename
def exist_post(file_id: int) -> bool:
try:
open(post_filename(file_id))
return True
except FileNotFoundError:
return False
def create_post(file_id: int, content: str) -> bool:
"""create a post"""
# check if the file already exists
update = exist_post(file_id)
# write into the file
with open(post_filename(file_id), "w", encoding="utf-8") as f:
f.write(content)
return update