From 8d045878bd78b311a10bb3038fad6c3e2f10385c Mon Sep 17 00:00:00 2001 From: Kalynovsky Valentin Date: Fri, 15 Dec 2023 00:09:36 +0200 Subject: [PATCH] Added admin login and post adding page --- blog/index.py | 64 ++++++++++++++++++++--- blog/resources/scripts/scripts.js | 47 +++++++++++++++++ blog/resources/style/style.css | 87 ++++++++++++++++++++++--------- blog/template/diary.html | 4 ++ blog/template/footer.html | 2 +- blog/template/header.html | 6 ++- blog/template/nav.html | 1 - blog/template/new_post.html | 37 +++++++++++++ 8 files changed, 212 insertions(+), 36 deletions(-) create mode 100644 blog/resources/scripts/scripts.js create mode 100644 blog/template/new_post.html diff --git a/blog/index.py b/blog/index.py index 517fe14..32e765e 100644 --- a/blog/index.py +++ b/blog/index.py @@ -1,4 +1,4 @@ -from flask import Flask, render_template, send_from_directory +from flask import Flask, render_template, send_from_directory, request, redirect, url_for, session import markdown2 import yaml import os @@ -7,21 +7,69 @@ app = Flask(__name__, template_folder='template', static_folder='resources') app.config['UPLOAD_FOLDER'] = os.path.join(os.getcwd(), 'files') +app.secret_key = 'your_secret_key' # Секретный ключ для подписи сессий +ADMIN_KEY = 'admin_key' # Ваш ключ для доступа к админским функциям + +# Проверка, является ли пользователь администратором +def is_admin(): + return session.get('admin', False) + +# Маршрут для входа в аккаунт (с ключом) +@app.route('/login') +def login(): + key = request.args.get('key', '') + if key == ADMIN_KEY: + session['admin'] = True + return redirect(url_for('diary')) + +# Маршрут для выхода из аккаунта +@app.route('/logout') +def logout(): + session.pop('admin', None) + return redirect(url_for('diary')) + +@app.route('/new_post') +def add_post(): + if not is_admin(): + return 'Access Denied' + return render_template('new_post.html', is_admin=is_admin()) + +@app.route('/save_post', methods=['POST']) +def save_post_route(): + # warning работает не корректно + title = request.form['title'] + description = request.form['description'] + content = request.form['content'] + + # Сохраняем файлы на сервер + saved_files = [] + for uploaded_file in request.files.getlist('file'): + filename = os.path.join(app.config['UPLOAD_FOLDER'], uploaded_file.filename) + uploaded_file.save(filename) + file_metadata = {'name': uploaded_file.filename, 'type': get_file_type(uploaded_file.filename)} + saved_files.append(file_metadata) + + # Формируем метаданные поста + post_metadata = f"name: {title}.md\ntitle: {title}\ndatetime: {datetime.now().strftime('%Y-%m-%d %I:%M %p')}\ndescription: {description}\nfiles: {files}\n\n#{title}\n\n{content}" + + # Сохраняем метаданные в файл + post_filename = f"{title}.md" + with open(os.path.join(app.config['UPLOAD_FOLDER'], post_filename), 'w', encoding='utf-8') as post_file: + post_file.write(post_metadata) + + return redirect(url_for('diary')) + @app.route('/') def home(): post_files = get_posts('posts', 5) post_contents = [load_post_metadata(file) for file in post_files] - return render_template('index.html', post_contents=post_contents) - -# @app.route('/contacts') -# def contacts(): -# return render_template('contacts.html') + return render_template('index.html', post_contents=post_contents, is_admin=is_admin()) @app.route('/diary') def diary(): post_files = get_posts('posts', 0) post_contents = [load_post_metadata(file) for file in post_files] - return render_template('diary.html', post_contents=post_contents) + return render_template('diary.html', post_contents=post_contents, is_admin=is_admin()) def get_posts(posts_directory, num_posts): post_files = [f for f in os.listdir(posts_directory) if os.path.isfile(os.path.join(posts_directory, f))] @@ -56,7 +104,7 @@ def load_post_metadata(post_content): def post(post_id): # Ваш код для загрузки и отображения полного содержания поста post_content = load_post_content(post_id) - return render_template('post.html', post_content=post_content) + return render_template('post.html', post_content=post_content, is_admin=is_admin()) def load_post_content(file_name): file_name = 'posts/' + str(file_name) diff --git a/blog/resources/scripts/scripts.js b/blog/resources/scripts/scripts.js new file mode 100644 index 0000000..955ad84 --- /dev/null +++ b/blog/resources/scripts/scripts.js @@ -0,0 +1,47 @@ +function auto_grow(element) { + element.style.height = "5px"; + element.style.height = (element.scrollHeight)+"px"; +} + +window.addEventListener('unload', function () { + const form = document.querySelector('form'); + form.reset(); // Очищаем все поля формы +}); + +// JavaScript для отображения выбранных файлов +function handleFileSelect(event) { + const files = event.target.files; + const fileList = document.getElementById('fileList'); + + // Обновляем список файлов + for (const file of files) { + const listItem = document.createElement('li'); + listItem.classList.add('file-item'); + + const link = document.createElement('a'); + link.href = URL.createObjectURL(file); + link.download = file.name; + + const icon = document.createElement('img'); + icon.src = 'resources/icons/' + getFileType(file.name) + '.png'; + icon.alt = getFileType(file.name) + ' Icon'; + icon.width = 128; + icon.height = 128; + icon.classList.add('file-icon'); + + const fileName = document.createTextNode(file.name); + + link.appendChild(icon); + link.appendChild(fileName); + listItem.appendChild(link); + + fileList.appendChild(listItem); + } +} + +// Получаем тип файла по расширению +function getFileType(fileName) { + const extension = fileName.split('.').pop().toLowerCase(); + // Ваш код определения типа файла по расширению, например, расширения 'pdf' -> 'PDF' + return extension.toUpperCase(); +} \ No newline at end of file diff --git a/blog/resources/style/style.css b/blog/resources/style/style.css index 8c54967..25a2e1d 100644 --- a/blog/resources/style/style.css +++ b/blog/resources/style/style.css @@ -1,53 +1,53 @@ body { - font-family: Arial, sans-serif; - margin: 0; - padding: 0; - background-color: #f4f4f4; + font-family: Arial, sans-serif; + margin: 0; + padding: 0; + background-color: #f4f4f4; } header { - background-color: #333; - color: #fff; - text-align: center; - padding: 1em; + background-color: #333; + color: #fff; + text-align: center; + padding: 1em; } nav { - background-color: #eee; - padding: 1em; - text-align: center; + background-color: #eee; + padding: 1em; + text-align: center; } nav a { - margin: 0 10px; - text-decoration: none; - color: #333; + margin: 0 10px; + text-decoration: none; + color: #333; } main { - max-width: 800px; - margin: 20px auto; - padding: 20px; - background-color: #fff; + max-width: 800px; + margin: 20px auto; + padding: 20px; + background-color: #fff; } footer { - padding: 1em; - background-color: #333; - color: #fff; + padding: 1em; + background-color: #333; + color: #fff; } .footer-container { - display: flex; - justify-content: space-between; + display: flex; + justify-content: space-between; } .column-left { padding-left: 50px; - width: 48%; /* Задайте ширину колонок по вашему усмотрению */ + width: 48%; /* Задайте ширину колонок по вашему усмотрению */ } .column-right { text-align: center; - width: 48%; /* Задайте ширину колонок по вашему усмотрению */ + width: 48%; /* Задайте ширину колонок по вашему усмотрению */ } .file-list { @@ -64,3 +64,40 @@ footer { width: 100%; height: auto; } + +form { + max-width: 600px; + margin: 0 auto; +} +input[type="text"], +textarea, +input[type="file"], +input[type="submit"] { + width: 100%; + padding: 10px; + margin-bottom: 15px; + border: 1px solid #ccc; + border-radius: 4px; + box-sizing: border-box; +} +textarea { + resize: none; /* Запрет изменения размера */ + overflow-y: hidden; /* Скрытие вертикального ползунка прокрутки */ + min-height: 150px; /* Высота для textarea */ +} +input[type="submit"] { + background-color: #4CAF50; + color: white; + cursor: pointer; +} +input[type="submit"]:hover { + background-color: #45a049; +} +/* Дополнительные стили для элемента input[type="file"] */ +input[type="file"] { + padding: 0; +} +/* Стили для подсказок (placeholders) */ +::placeholder { + color: #999; +} diff --git a/blog/template/diary.html b/blog/template/diary.html index 3e7c09a..95d918c 100644 --- a/blog/template/diary.html +++ b/blog/template/diary.html @@ -13,6 +13,10 @@ {% include 'nav.html' %}
+ {% if is_admin %} + Додати пост + {% endif %} + {% for metadata in post_contents %}
diff --git a/blog/template/footer.html b/blog/template/footer.html index 55498d6..e67cf3c 100644 --- a/blog/template/footer.html +++ b/blog/template/footer.html @@ -1,7 +1,7 @@