我在烧瓶上制作了一个网站,用户可以在那里上传演示文稿或Word文件,将其正确上传到服务器,但无法下载;错误写在标题中。
代码是。 错误:检测到未知服务器错误。 请重试或联系您的管理员。from flask import Flask, render_template, request, redirect, url_for,session,flash
from flask_bcrypt import generate_password_hash, check_password_hash
import psycopg2
from psycopg2 import sql
import os
from datetime import datetime, timedelta
from flask_login import login_user, current_user
from flask_cors import CORS
from werkzeug.utils import secure_filename
app = Flask(__name__, template_folder='C:/Users/User/Desktop/veliy/code', static_folder='C:/Users/User/Desktop/veliy/static')
CORS(app)
app.secret_key = 'SFgJSDfHUISFGJK454593VfVBR7BsSR8473dBsDSdbjsrhhkhluFG474ERDFDsSFSdFDS'
UPLOAD_FOLDER = 'uploads'
app.permanent_session_lifetime = timedelta(days = 25)
# Создаем папку, если ее нет
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def create_db():
try:
with psycopg2.connect(dbname="Usermans", user="postgres", password="moyasemya56", host="localhost", port="5432") as conn:
with conn.cursor() as cur:
firstdata = '''
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(10) UNIQUE NOT NULL,
password VARCHAR(100) NOT NULL, -- Increased length for hashed password
email VARCHAR(20) UNIQUE NOT NULL
);
'''
cur.execute(firstdata)
conn.commit()
except Exception as e:
print(f"Error creating database: {e}")
create_db()
def get_user_info_by_id(user_id):
try:
with psycopg2.connect(dbname="Usermans", user="postgres", password="moyasemya56", host="localhost", port="5432") as conn:
with conn.cursor() as cur:
query = "SELECT * FROM users WHERE id = %s"
cur.execute(query, (user_id,))
user = cur.fetchone()
if user:
user_info = {
'id': user[0],
'name': user[1],
'email': user[3]
# Добавьте другие поля пользователя по необходимости
}
return user_info
else:
return None
except Exception as e:
print(f"Error getting user info: {e}")
return None
@app.route('/', methods=['POST', 'GET'])
def Main():
return render_template('home.html')
@app.route('/support')
def Support():
query = request.args.get('query', '').lower()
# Получаем список всех презентаций
all_presentations = []
for filename in os.listdir(app.config['UPLOAD_FOLDER']):
if filename.endswith(('.ppt', '.pptx')):
all_presentations.append(filename)
# Фильтруем презентации по запросу
filtered_presentations = []
for presentation in all_presentations:
if query in presentation.lower():
filtered_presentations.append(presentation)
return render_template('VeliyAbout1.html',presentation_filenames=filtered_presentations )
@app.route('/login', methods=['POST', 'GET'])
def Login():
if 'user_id' in session:
return redirect(url_for('personalpage', user_id=session.get('user_id') ))
user_id = None
if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form:
username = request.form['username']
password = generate_password_hash(request.form['password']).decode('utf-8') # Хеширование пароля
email = request.form['email']
try:
with psycopg2.connect(dbname="Usermans", user="postgres", password="moyasemya56", host="localhost", port="5432") as conn:
with conn.cursor() as cur:
insert_users = sql.SQL("INSERT INTO users (name, password, email) VALUES (%s, %s, %s);")
cur.execute(insert_users, (username, password, email))
user_id = cur.fetchone()[0]
conn.commit()
except Exception as e:
print(f"Error inserting user data: {e}")
session['user_id'] = user_id
return redirect(url_for('personalpage'))
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
if check(email, password):
return redirect(url_for('personalpage', user_id=session.get('user_id') ))
else:
print("Авторизация не удалась. Неверный email или пароль.")
return render_template('register.html')
def check(email, password):
try:
with psycopg2.connect(dbname="Usermans", user="postgres", password="moyasemya56", host="localhost", port="5432") as conn:
with conn.cursor() as cur:
query = "SELECT * FROM users WHERE email = %s"
cur.execute(query, (email,))
user = cur.fetchone()
if user and check_password_hash(user[2], password): # Check hashed password
session['user_id'] = user[0]
print("Авторизация успешна!")
return True
else:
print("Авторизация не удалась. Неверный email или пароль.")
except Exception as e:
print(f"Error checking credentials: {e}")
return False
def get_user_id_by_email(email):
try:
with psycopg2.connect(dbname="Usermans", user="postgres", password="moyasemya56", host="localhost",
port="5432") as conn:
with conn.cursor() as cur:
query = "SELECT id FROM users WHERE email = %s"
cur.execute(query, (email,))
user_id = cur.fetchone()
if user_id:
return user_id[0]
else:
return None
except Exception as e:
print(f"Error getting user id by email: {e}")
return None
@app.route('/personalpage',methods=['POST', 'GET'])
def personalpage():
filenames = os.listdir(app.config['UPLOAD_FOLDER'])
if 'user_id' in session :
user_id = session['user_id']
user_info = get_user_info_by_id(user_id) # Замените на ваш метод получения информации о пользователе
if user_info:
return render_template('grge1.html', user_id=session.get('user_id') )
else:
return "Ошибка: Пользователь не найден", 404
else:
return redirect(url_for('Login'))
return render_template('grge1.html', filenames=filenames, user_info=user_info )
@app.route('/trends')
def Trends():
return render_template('ERROR.html')
@app.route('/catalog', methods=['POST', 'GET'])
def Presentations():
presentation_filenames = [filename for filename in os.listdir(app.config['UPLOAD_FOLDER']) if filename.endswith(('.ppt', '.pptx'))]
word_doc_filenames = [filename for filename in os.listdir(app.config['UPLOAD_FOLDER']) if filename.endswith(('.doc', '.docx'))]
pdf_filenames = [filename for filename in os.listdir(app.config['UPLOAD_FOLDER']) if filename.endswith('.pdf')]
return render_template('pr.html', presentation_filenames=presentation_filenames, word_doc_filenames=word_doc_filenames, pdf_filenames=pdf_filenames )
@app.route('/uploads/<filename>')
def download_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename , as_attachment=True, mimetype='application/octet-stream' )
@app.route('/upload', methods=['POST'])
def upload():
if 'wordFile' not in request.files or 'presentationFile' not in request.files:
return "Ошибка: Отсутствуют файлы для загрузки."
word_file = request.files['wordFile']
presentation_file = request.files['presentationFile']
if word_file and presentation_file :
word_filename = os.path.join(app.config['UPLOAD_FOLDER'], word_file.filename)
presentation_filename = os.path.join(app.config['UPLOAD_FOLDER'], presentation_file.filename)
word_file.save(word_filename)
presentation_file.save(presentation_filename)
return "Файлы успешно загружены."
else:
return "Ошибка: Не удалось загрузить файлы."
@app.route('/search', methods=['POST'])
def search():
return render_template('index.html')
@app.errorhandler(Exception)
def handle_error(e):
return str(e), 500
@app.errorhandler(404)
def page_not_found(e):
return render_template('ERROR.html'), 404
if __name__ == '__main__':
app.run(debug=True, port=8080 )
我不知道如何更正我的代码