Quart框架渲染HTML/CSS静态资源时出现404错误求助
Quart框架静态资源加载404问题解决
问题现象
使用Quart开发网页时,PyCharm预览HTML、CSS及图片显示正常,但运行代码后,浏览器提示style.css和图片资源返回404状态,无法加载。
相关代码及文件结构
main.py
from quart import Quart, render_template, redirect, url_for app = Quart(__name__) @app.route("/") async def index(): return await render_template("index.html") app.run(debug=True)
index.html
<!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="index/style.css"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Some title</title> </head> <body> <div class="container"> <img src="index/some_image.png" alt="something" style="width:50%;"> <a href="/login"> <button class="button button_Login">Login</button> </a> </div> </body> </html>
style.css
.container { position: relative; text-align: center; } .container .button_Login { position: absolute; bottom: 1%; left: 50%; transform: translate(-50%, -50%); background-color: black; border: 3px solid #eeccff; color: white; padding: 15px 32px; text-align: center; border-radius: 4px; font-size: 20px; transition-duration: 0.4s } .container .button_Login:hover { color: black; background-color: #eeccff; } .button_Login:active { position: relative; top: 2px; } body { background: black; }
原文件结构
app templates index some_image.png style.css index.html main.py
浏览器报错
Failed to load resource: the server responded with a status of 404 () style.css:1
Failed to load resource: the server responded with a status of 404 () Amethyst.png:1
Failed to load resource: the server responded with a status of 404 () style.css:1
问题原因
Quart遵循与Flask一致的静态资源约定:默认仅识别static目录下的静态文件(CSS、图片、JS等),而你将静态资源放在了templates文件夹内,服务器无法解析该路径;同时HTML中直接使用相对路径引用资源,不符合Quart的静态资源路由规则。
解决步骤
1. 调整文件结构
创建static目录,将静态资源移动到该目录下,调整后的结构如下:
app static index some_image.png style.css templates index.html main.py
2. 修改HTML中的资源引用路径
使用Quart提供的url_for函数生成正确的静态资源URL,修改后的index.html代码如下:
<!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="{{ url_for('static', filename='index/style.css') }}"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Some title</title> </head> <body> <div class="container"> <img src="{{ url_for('static', filename='index/some_image.png') }}" alt="something" style="width:50%;"> <a href="/login"> <button class="button button_Login">Login</button> </a> </div> </body> </html>
3. 验证运行
重新启动Quart服务,浏览器访问页面即可正常加载CSS和图片资源。
内容的提问来源于stack exchange,提问作者PHOENIX33201
相关产品推荐
相关产品推荐

