8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

文件不会从我的烧瓶网站下载

Michael Butscher 7月前

124 0
我在烧瓶上制作了一个网站,用户可以在那里上传演示文稿或Word文件,将其正确上传到服务器,但无法下载;错误写在标题中。 代码...

我在烧瓶上制作了一个网站,用户可以在那里上传演示文稿或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 )

我不知道如何更正我的代码

帖子版权声明 1、本帖标题: 文件不会从我的烧瓶网站下载
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由Michael Butscher在本站《python》版块原创发布, 转载请注明出处!
最新回复 (0)
  • 您在服务器过程的输出中看到了什么? 您可能也应该禁用
  • 确保使用“ send_from_directory”正确使用“下载_FILE”路由。 验证上传的文件存储在正确的目录中。 使用各种文件类型的测试下载。 处理上传错误并实施安全措施,例如文件类型验证。
  • 谁可以帮助我?目录是正确的,文件通常保存在此目录中,因为当我下载文件时。
  • 请修剪您的代码,以便更轻松地找到您的问题。 遵循以下准则来创建一个
返回
作者最近主题: