我正在学习烧瓶,遇到了一些问题
当我编写这样的代码时:
@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路径没有更改。。为什么
我心碎了,睡不着。。请帮帮我
除了
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
加载该资源这可以解释你所看到的行为
另一方面,考虑这个测试应用程序:
与位于
templates/index.html
的以下模板配对:然后点击并观察控制台中的资产请求(他们会给出404个错误,因为我还没有实际创建CSS文件,这只是为了显示浏览器请求的内容):
加载URL:
http://localhost:5000/a
:加载URL:
http://localhost:5000/b/
:当然,包含这些资产的正确方法是使用
url_for
函数因此,如果我将模板更新为包含:
然后提出同样的要求:
加载URL:
http://localhost:5000/a
:加载URL:
http://localhost:5000/b/
:如您在此处所见,无论端点是否有尾随斜杠,静态资源的正确路径将始终被渲染
相关问题 更多 >
编程相关推荐