【问题标题】:Python Not Finding CSS FilePython 找不到 CSS 文件
【发布时间】:2015-02-06 15:59:58
【问题描述】:

您好,我是使用 python 和 web 程序的新手,我正在尝试制作一个使用 CSS 样式表的基本网站。我有三个文件:app.py、index.html 和 style.css。它们都在同一个目录中。当我运行 app.py 并转到 localhost:8080 时,它显示“Hello World!”,但它没有 style.css 文件中的样式,并且我的终端显示“HTTP/1.1 GET /style.css” - 404 Not Found .但是,当我在 chrome 中打开我的 index.html 文件而不使用 app.py 文件时,它确实具有样式格式。有什么帮助吗?提前致谢。我的代码如下:

app.py:

import web

urls = (
    '/', 'Index'
)

app = web.application(urls, globals())

web.config.debug = True

class Index(object):

    def __init__(self):
        self.render = web.template.render('.')

    def GET(self):
        return self.render.index()

if __name__ == '__main__':
    app.run()

index.html:

<!DOCTYPE html>
<html>
    <head>
        <link type="text/css" rel="stylesheet" href="style.css" />
        <title>Basic Web Project</title>
    </head>
    <body>
        <p>Hello World!</p>
    </body>
</html>

style.css:

p {
    color: green;
    font-size: 22px;
}

【问题讨论】:

    标签: python html css


    【解决方案1】:

    当您指定&lt;link type="text/css" rel="stylesheet" href="style.css" /&gt; 时,您对您的网络浏览器说以下内容:style.css 与 index.html 处于同一级别

    让我举个例子:

    /app
       index.html
       style.css
    

    如果您从浏览器打开 index.html,您会转到以下网址

    file://some/directory/app/index.html
    

    )它和file://some/directory/app/一样,因为浏览器在显示网页时总是会搜索索引) 当在这个index.html 中,浏览器找到您指定的&lt;link&gt; 时,它将在以下网址下搜索style.cssfile://some/directory/app/style.css 当然它会找到那个文件。

    现在是有趣的部分。

    当您打开localhost:8080 时,它会显示localhost:8080/index.html,因为您的Web 应用程序(您运行的那个python 脚本)知道当有人访问该网址时该怎么做(因为您在urls 变量中定义了它你创建了class)

    但是当浏览器在此页面上找到&lt;link&gt; 标签时,他会尝试转到localhost:8080/style.css,您的网络应用不知道如何处理,因为您没有在应用中指定它。

    现在解决方案: 您必须为 /style.cssclass 定义一个 url,它将为您呈现该网页。

    【讨论】:

      【解决方案2】:

      您是否尝试将style.css 添加到urls,您的应用程序对/style.css 获取请求一无所知,可能这就是它返回404 的原因。

      【讨论】:

        猜你喜欢
        • 2020-04-30
        • 2013-01-11
        • 1970-01-01
        • 2018-06-09
        • 2015-03-28
        • 1970-01-01
        • 1970-01-01
        • 2023-02-19
        相关资源
        最近更新 更多