【问题标题】:Can't get the right url_for static file in Flask locally无法在本地获取 Flask 中正确的 url_for 静态文件
【发布时间】:2015-12-23 19:08:17
【问题描述】:

我有一个可以做我需要的网络服务器,但为了开发应用程序,我希望我的一些静态文件在本地提供。 例如,我有 /Desktop/project_folder/static/jsons/example.json。 我试试:

print(url_for('static', filename='jsons/example.json'))
/static/jsons/example.json

我得到的是 /static/jsons/example.json。

我尝试通过以下方式设置静态路径:

app = Flask(__name__, static_folder='/Desktop/project_folder/static')
print(app.static_folder)
/Desktop/project_folder/static
url = url_for('static', filename='jsons/example.json')
print(url)
/static/jsons/example.json

我在这里检查了几十个类似的问题,他们都建议调整 static_folder 或 static_url_path 但这些都没有帮助 - 我刚刚开始在我的静态文件夹中的所有其他资源上遇到 404 错误。我也试过 send_from_directory 但我得到的是 werkzeug.wrappers.Response 对象,我无法从中获取数据。

更新: 我尝试使用以下方式加载此 json:

json_loaded = json.load(requests.get(url).text)

然后得到一个错误:MissingSchema: Invalid URL '/static/jsons/example.json': No schema provided.

【问题讨论】:

  • /static/jsons/example.json 有什么问题?你有多个静态文件夹吗?
  • 我更新了问题,我尝试通过请求获取此 url 的内容,并得到一个错误:MissingSchema: Invalid URL '/static/jsons/example.json': No schema provided.
  • 我开始感觉到,用一些 cdn 来保存静态文件,而不用费心通过 Flask 提供它们,这仍然更容易。

标签: flask static-files


【解决方案1】:

您需要告诉请求文件所在的位置。一条路是不够的。您还需要包含方案和域、主机名或 IP 地址。只有端口是可选的。

requests.get('http://example.com/path/to/file')

由于您使用url_for 为您生成 URL,因此您需要告诉它为您包含此信息。

url_for('static', filename='jsons/example.json', _external=True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2013-04-27
    • 2012-11-22
    • 1970-01-01
    • 2013-08-09
    • 2013-10-30
    相关资源
    最近更新 更多