【问题标题】:Python Error [Errno 36]: File name too longPython 错误 [Errno 36]:文件名太长
【发布时间】:2016-12-06 01:46:47
【问题描述】:

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

[Errno 36] 文件名太长:'/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)

有人知道解决方案吗?非常感谢。

【问题讨论】:

  • 你能拉出os.path.join(SITE_ROOT, "static/data", "btc.json")并打印它返回的内容吗?

标签: python file flask filenames errno


【解决方案1】:

当 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")

【讨论】:

  • 谢谢它的工作原理!但是我如何返回一个不是来自目录文件的巨大字符串呢?
猜你喜欢
  • 1970-01-01
  • 2015-07-05
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多