【问题标题】:Various errors in Python Flask [closed]Python Flask中的各种错误[关闭]
【发布时间】:2020-05-15 11:19:04
【问题描述】:

我最近做了一个代码,就像没有任何 index.html 的 Apache 服务器一样工作

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

下面是我的工作照片

结构照片(位于C:\Users\YourUsername\Documents\webserver\

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

  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)

谁能帮助我解决这些错误,或者只是改进我的代码?谢谢

【问题讨论】:

  • 这段代码到底发生了什么?您打算将所有 with open() 上下文管理器堆叠起来做什么?请退后一步,使用mega tutorial 之类的东西,你会很好地重新审视一些基础知识。恕我直言,您似乎跳过了一些知识试金石,让自己陷入了困境
  • 好的...这里发生了很多事情。您发布的 CSS 与图像完全无关。他们只是把帖子弄得乱七八糟。需要做很多工作。我会用一些提示创建一个答案。
  • 感谢@roganjosh 的提示,我知道我的代码一团糟,但我认为它并没有那么糟糕。我一定会看那个链接
  • 您正在处理后端的所有模板逻辑。 Flask 带有jinja2,你可以利用它来构建你的模板。特别是(虽然不是唯一的)像render_template
  • 感谢@blueteeth 的建议,我不擅长在 SO 上发帖,我还有很多东西要学

标签: python html python-3.x flask file-not-found


【解决方案1】:

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

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

也许可以按照有关如何创建烧瓶应用的指南进行操作。这个很不错:https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

您不必一直遵循它。

祝你好运!当您有下一个版本时,请随时再次发布。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-27
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多