Python 错误 [Errno 36]: 文件名太长

Python Error [Errno 36]: File name too long

我搜索过这个错误,但找不到如何处理它。尝试打开文件时出现以下错误:

[Errno 36] File name too long: '/var/www/FlaskApp/FlaskApp/templates/

这是我的简单代码。我正在尝试打开一个 json 文件并使用 Flask 将其渲染到网站中:

@app.route("/showjson/")
def showjson():
    SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
    data_in = open(os.path.join(SITE_ROOT, "static/data", "btc.json"), "r")
    data_out = ""
    for line in data_in:
        data_out += line.rstrip()
    data_in.close()
    return render_template(data_out)

有人知道解决办法吗?非常感谢。

当 render_template 函数查找模板文件的文件名时,您将整个 JSON 文件传递​​给它。这就是您收到文件名太长错误的原因。

您可以使用send_from_directory函数发送JSON文件。先导入函数:

from flask import send_from_directory

然后像这样使用它:

@app.route("/showjson/")
def showjson(path):
    SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
    return send_from_directory(os.path.join(SITE_ROOT, "static/data"), "btc.json")