当我编写app.route('/home')并编辑它时Flaskapp.route('/home/')并还原它

2024-04-23 18:51:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习烧瓶,遇到了一些问题

当我编写这样的代码时:

@app.route("/reference")
def reference():
    return render_template("reference.html", css="reference", records=records)

页面http://127.0.0.1:5000/reference正在运行

然后,我在flask文档中找到了“尾部斜杠”

我想应用它,所以我编辑代码如下:

@app.route("/reference/")
def reference():
    return render_template("reference.html", css="reference", records=records)

它也起作用了http://127.0.0.1:5000/reference/

但是,一些问题正在出现

浏览器无法通过python终端中更改的日志读取我的css文件(在html链接中..href=blabla)

GET /static/css/style.css HTTP/1.1 << before changing
GET /reference/static/css/style.css HTTP/1.1 << after changing

我重定向了css文件路径

href="static/css/style.css"
to
href="../static/css/style.css"

它是有效的

我想了解“尾随斜杠”是怎么做的

因此,我将我的代码重置为第一个代码

然后出现了404未找到错误,我得到了一个未更改的日志

"GET /reference HTTP/1.1" << log for first code
"GET /reference/ HTTP/1.1" << log for second code
"GET /reference/ HTTP/1.1" << log for reset code (== first code)

我有个问题发生了什么事?

我不明白它为什么不像以前那样运行

我读了https://flask.palletsprojects.com/en/2.0.x/quickstart/#unique-urls-redirection-behavior

但我还是不明白发生了什么

为什么要更改路径。。为什么GET路径没有更改。。为什么

我心碎了,睡不着。。请帮帮我


1条回答
网友
1楼 · 发布于 2024-04-23 18:51:14

除了unique-urls-redirection-behavior文档所说的之外,当您使用像<img src='some_url'><link href='some_url'>这样的标记时,行为可能会有所不同,因为这些URL是由浏览器加载的

因此,对于像@app.route("/reference")这样的路由装饰器,它在浏览器中作为example.com/reference加载,带有href="subpath/file.css"的链接标记会导致浏览器从example.com/subpath/file.css加载该资源

另一方面,像@app.route("/reference/")(带尾随斜杠)这样的路由装饰器在浏览器中加载为example.com/reference/(同样,带尾随斜杠),带有href="subpath/file.css"的链接标记会导致浏览器从example.com/reference/subpath/file.css加载该资源

这可以解释你所看到的行为


另一方面,考虑这个测试应用程序:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/a')
def a(): return render_template('index.html')

@app.route('/b/') # Note trailing slash
def b(): return render_template('index.html')

与位于templates/index.html的以下模板配对:

<html>
<head>
    <link rel='stylesheet'  href='subpath/file.css' />
</head>

然后点击并观察控制台中的资产请求(他们会给出404个错误,因为我还没有实际创建CSS文件,这只是为了显示浏览器请求的内容):

加载URL:http://localhost:5000/a

"GET /a HTTP/1.1" 200 -
"GET /subpath/file.css HTTP/1.1" 404 -

加载URL:http://localhost:5000/b/

"GET /b/ HTTP/1.1" 200 -
"GET /b/subpath/file.css HTTP/1.1" 404 -

当然,包含这些资产的正确方法是使用url_for函数

因此,如果我将模板更新为包含:

  <link rel='stylesheet'  href='{{ url_for("static", filename="file.css") }}' />

然后提出同样的要求:

加载URL:http://localhost:5000/a

"GET /a HTTP/1.1" 200 -
"GET /static/file.css HTTP/1.1" 404 -

加载URL:http://localhost:5000/b/

"GET /b/ HTTP/1.1" 200 -
"GET /static/file.css HTTP/1.1" 404 -

如您在此处所见,无论端点是否有尾随斜杠,静态资源的正确路径将始终被渲染

相关问题 更多 >