烧瓶GET请求发送到错误的路径,导致404

时间:2020-07-18 16:08:13

标签: python flask

我的烧瓶应用程序出现问题。

我有以下代码:

@app.route("/note")
def note():
  return render_template("note.html")

@app.route("/notes/<notename>")
def notes(notename):
  return render_template("note.html")

两者均应返回相同的内容,但问题是,当应用尝试发出GET请求以获取该页面的js和css文件时,具有/ notes /路由的人无法获取这些js和css文件因为GET请求指向错误的路径。

我将显示一个示例:

当我导航至example.com/时,输出为:

[18/Jul/2020 08:59:11] "GET /note HTTP/1.1" 200 -
[18/Jul/2020 08:59:11] "GET /static/css/layout/layout.css HTTP/1.1" 304 -
[18/Jul/2020 08:59:11] "GET /static/js/notes/notes.js HTTP/1.1" 304 -
[18/Jul/2020 08:59:11] "GET /static/css/notes/notes.css HTTP/1.1" 200 -
[18/Jul/2020 08:59:11] "GET /static/css/notes/buttons.css HTTP/1.1" 304 -

一切正常。

但是,当我转到example.com/notes/something时,这里的页面加载时没有JS或CSS样式,并且在控制台中我得到了:

[18/Jul/2020 09:01:34] "GET /notes/somethinghere HTTP/1.1" 200 -
[18/Jul/2020 09:01:35] "GET /notes/static/css/notes/notes.css HTTP/1.1" 404  -
[18/Jul/2020 09:01:35] "GET /notes/static/js/notes/notes.js HTTP/1.1" 404 -
[18/Jul/2020 09:01:35] "GET /notes/static/css/notes/buttons.css HTTP/1.1" 404 -
[18/Jul/2020 09:01:35] "GET /notes/static/js/notes/notes.js HTTP/1.1" 404 -

问题在于GET请求以/ notes开头,因此找不到要加载JS和CSS文件的文件夹。 我提出的一些肮脏的修复方法是创建一个notes文件夹,然后在其中克隆js和css文件,以便它找到它们,或者只是从URL路径中删除/ notes,但这些都不是最完美的。

有没有一种方法可以更改路径,以便在进入example.com/notes/somethinghere时不以/ notes开头?

1 个答案:

答案 0 :(得分:0)

您的问题可能存在于notes.html中。

我猜您包含的路径中没有前导/

<link href='static/css/somefile.css'>

您应该执行以下操作:

<link href='/static/css/somefile.css'>

当然在Flask中,您可以使用url_for函数来动态生成此代码:

<link href'{{ url_for('static', filename='css/somefile.css') }}'>