【问题标题】:Query regarding url_for in Flask [duplicate]Flask中有关url_for的查询[重复]
【发布时间】:2020-11-16 13:35:20
【问题描述】:

我一直在做一个 Flask 项目。但是我遇到了一个问题。
要正确理解我的问题,您必须查看我的文件夹结构。





我想使用 url_for 语法访问我的 models.py 文件中的“./static/data/wordlist.txt”。
这是我写的:url_for('static', filename='data/wordlist.txt')

但是烧瓶给我一个错误说:FileNotFoundError: [Errno 2] No such file or directory: '/static/data/wordlist.txt'

任何关于我应该做什么的帮助都会很棒!!

【问题讨论】:

  • 正在构建的 URL 的目的是什么(你打算用它做什么)
  • 我正在制作一个网址缩短器。 wordlist.txt 包含许多随机单词,程序从中随机选择一个单词并将其添加到数据库中。为此,我想访问models.py中的wordlist.txt
  • 请注意,我已经尝试使用with open("./static/data/wordlist.txt) as file 执行此操作。但它给了我同样的错误。
  • 也许你应该使用绝对路径,dir_name = os.path.dirname(os.path.abspath(__file__)) 并使用wordlist_path = os.path.join(dir_name, "static/data/wordlist.txt")
  • 我的目标是将其托管在在线服务器中。所以给绝对路径不是我的选择。我必须使用 url_for。

标签: python flask url-for


【解决方案1】:

使用app.url_root 获取与您的代码相关的路径。

wordlist_path = os.path.join(app.root_path, "static/data/wordlist.txt")

with open(wordlist_path) as f:
    ...

【讨论】:

    猜你喜欢
    • 2016-04-30
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多