Python Flask中的各种错误

问题描述 投票:-1回答:1

我最近制作了一个代码,该代码的工作原理类似于没有任何index.html的Apache服务器

Apache server without any index.html

问题是我的代码确实有错误,我遇到了不同的错误(这就是为什么我没有在标题中写它们)

下面有我的照片

My work

结构图(位于C:\Users\YourUsername\Documents\webserver\中)

structure

正如我之前说的,我得到了不同的错误:

  1. [进入两个文件夹或更深的文件夹,然后尝试使用浏览器箭头返回,然后单击任何文件/文件夹时,我得到FileNotFoundError
  2. [进入两个文件夹或更深的文件夹,然后尝试使用“向上文件夹”按钮([ .. ])给我的效果相当于abort(404)

.CSS文件的语法有点特殊,但是内容只是标准CSS

{
    color: black;
}

现在我们有了主要代码,webserver.py

# -*- coding: utf-8 -*-

from flask import Flask, redirect, url_for, send_from_directory
from getpass import getuser
import os

### VARS ###

app = Flask('__main__')

SEP = os.sep

FOLDER_HOME = f'C:{SEP}Users{SEP}{getuser()}{SEP}Documents{SEP}webserver{SEP}'
FOLDER_STYLE = f'{FOLDER_HOME}styles{SEP}'
ONLINE_PATH = f''
app.config["ABS_PATH"] = f'C:{SEP}Users{SEP}{getuser()}{SEP}Documents{SEP}webserver{SEP}online{SEP}'

with open(f'{FOLDER_STYLE}STYLE_HTML.css', 'r', encoding='utf-8') as file: STYLE = " ".join(''.join(file.readlines()).split())
with open(f'{FOLDER_STYLE}STYLE_A.css', 'r', encoding='utf-8') as file: STYLE_A = " ".join(''.join(file.readlines()).split())
with open(f'{FOLDER_STYLE}STYLE_CLASS_ERROR.css', 'r', encoding='utf-8') as file: STYLE_ERROR = " ".join(''.join(file.readlines()).split())
with open(f'{FOLDER_STYLE}STYLE_CLASS_PDBTM.css', 'r', encoding='utf-8') as file: STYLE_PADDING_BOTTOM = " ".join(''.join(file.readlines()).split())
with open(f'{FOLDER_STYLE}STYLE_CLASS_HOME.css', 'r', encoding='utf-8') as file: STYLE_CLASS_HOME = " ".join(''.join(file.readlines()).split())

index_def1 = ['<!DOCTYPE html>', '<html>', '<head>', '<meta charset="utf-8">', f'<style type="text/css">html{STYLE} a{STYLE_A} .error{STYLE_ERROR} .pdbtm{STYLE_PADDING_BOTTOM} .home{STYLE_CLASS_HOME}</style>', f'<title>Index of /{ONLINE_PATH.replace(f"{SEP}", "/")}</title>', '</head>', '<body>', f'<h1 align="center">Index of /{ONLINE_PATH.replace(f"{SEP}", "/")}</h1>', '<br>', '<ul>', '[<a class="home pdbtm" href="/">HOME</a>]<br>', f'[<a class="home pdbtm" href="/{ONLINE_PATH}"> .. </a>]<br>']
index_file = []
index_def2 = ['</ul>', '</body>', '</html>']

### END ###

### FUNCTIONS ###

def process_html(dirs_list, files_list):
    body = []
    body.append('<br> --- Directorys --- </br>')
    if dirs_list == []: body.append('<h2 class="error">No dirs found</h2>')
    else:
        for dirs in dirs_list:
            body.append(f'<li class="pdbtm"><a href="/{dirs}">{dirs}/</a></li>')
    body.append('<br> --- Files --- </br>')
    if files_list == []: body.append('<h2 class="error">No files found</h2>')
    else:
        for files in files_list:
            body.append(f'<li class="pdbtm"><a href="{files}">{files}</a></li>')
    return body

def process_all(path, listed_directory):
    dirs = []
    files = []
    for item in listed_directory:
        if os.path.isfile(f'{path}{item}') == True: files.append(item)
        else: dirs.append(item)
    return dirs, files

### END ###

### ROUTES ###

@app.route('/')
def main():
    global index_file
    global ONLINE_PATH
    global index_def1
    ONLINE_PATH = ''
    index_def1 = ['<!DOCTYPE html>', '<html>', '<head>', '<meta charset="utf-8">', f'<style type="text/css">html{STYLE} a{STYLE_A} .error{STYLE_ERROR} .pdbtm{STYLE_PADDING_BOTTOM} .home{STYLE_CLASS_HOME}</style>', f'<title>Index of /{ONLINE_PATH.replace(f"{SEP}", "/")}</title>', '</head>', '<body>', f'<h1 align="center">Index of /{ONLINE_PATH.replace(f"{SEP}", "/")}</h1>', '<br>', '<ul>', '[<a class="home pdbtm" href="/">HOME</a>]<br>', f'[<a class="home pdbtm" href="/{ONLINE_PATH}"> .. </a>]<br>']
    app.config["ABS_PATH"] = f'C:{SEP}Users{SEP}{getuser()}{SEP}Documents{SEP}webserver{SEP}online{SEP}'
    list_of_files = os.listdir(app.config["ABS_PATH"])
    dirs, files = process_all(app.config["ABS_PATH"], list_of_files)
    index_file = process_html(dirs, files)
    index_comp = [index_def1, index_file, index_def2]
    index = [item for sublist in index_comp for item in sublist]
    return ''.join(index)

@app.route("/<path>")
def get_file(path):
    while True:
        try: 
            return send_from_directory(app.config["ABS_PATH"], filename=path, as_attachment=True)
        except:
            global index_file
            global ONLINE_PATH
            global index_def1

            if path not in ONLINE_PATH: ONLINE_PATH += f'{path}{SEP}'
            else: ONLINE_PATH = f'{path}{SEP}'
            xyz = ONLINE_PATH.replace(path, '')
            xyz = xyz[:-1]
            xyz = ''.join(xyz)
            index_def1 = ['<!DOCTYPE html>', '<html>', '<head>', '<meta charset="utf-8">', f'<style type="text/css">html{STYLE} a{STYLE_A} .error{STYLE_ERROR} .pdbtm{STYLE_PADDING_BOTTOM} .home{STYLE_CLASS_HOME}</style>', f'<title>Index of /{ONLINE_PATH.replace(f"{SEP}", "/")}</title>', '</head>', '<body>', f'<h1 align="center">Index of /{ONLINE_PATH.replace(f"{SEP}", "/")}</h1>', '<br>', '<ul>', '[<a class="home pdbtm" href="/">HOME</a>]<br>', f'[<a class="home pdbtm" href="/{xyz}"> .. </a>]<br>']
            app.config["ABS_PATH"] = f'C:{SEP}Users{SEP}{getuser()}{SEP}Documents{SEP}webserver{SEP}online{SEP}{ONLINE_PATH}'

            list_of_files = os.listdir(app.config["ABS_PATH"])
            dirs, files = process_all(app.config["ABS_PATH"], list_of_files)
            index_file = process_html(dirs, files)
            index_comp = [index_def1, index_file, index_def2]
            index = [item for sublist in index_comp for item in sublist]
            return ''.join(index)

### END ###

app.run(host='0.0.0.0', port=80, debug=True)

有人可以通过改进我的代码来帮助我解决这些错误吗?谢谢

file-not-found
1个回答
1
投票

这需要大量工作。在这种状态下,我无法回答问题,但是我可以给您一些提示:

  1. 请勿从字符串生成HTML。改用模板:https://flask.palletsprojects.com/en/1.1.x/tutorial/templates/
    • 模板参数是您的朋友。您可以将文件作为列表存储在当前目录中。甚至更好的是,为路径创建一个抽象,并提供这些列表。
    • 这也将使您摆脱所有这些随机CSS文件。
  2. 请勿使用global。 Python几乎不需要它们。
  3. [pathlib]会真正帮助您,而不是os.pathhttps://docs.python.org/3/library/pathlib.html
  4. 您不需要2条路线。您只需要一个/<path>。如果为空,则加载根目录,否则加载该路径中的任何内容。

也许遵循有关如何创建Flask应用程序的指南。这个非常好:https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

您不必一直遵循它。

祝你好运!下一个版本时,请再次发表。

© www.soinside.com 2019 - 2024. All rights reserved.