CherryPy似乎找不到CSS脚本(静态或绝对路径)

2024-06-10 02:39:29 发布

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

我使用cherryPy框架为我的站点提供服务,但它似乎找不到静态路径或绝对路径的css脚本。如果我直接转到索引.tmpl文件通过浏览器,但当我通过cherrypy请求它时,它不使用css脚本。在

根目录结构:

site.py
template/index.tmpl
static/css/main.css

站点.py

^{pr2}$

模板/索引.tmpl

<!DOCTYPE html>
<html>
<head>
    #for $script in $css_scripts:
        <link rel="stylesheet" href="$script" type="text/css" />
    #end for
        <link rel="stylesheet" href="C:/ABSOLUTE/PATH/main.css" type="text/css" />
</head>
<body>
        <! MY HTML CODE IS HERE>
</body>
</html>

我做错什么了?在

编辑
我已经尝试使用static/css/main.css作为静态路径
我也尝试过相对路径,相对于站点.py相对于索引.tmpl

这是我得到的错误:

GET http://localhost:2000/static/css/main.css 404 (Not Found)  

Tags: py路径脚本for站点mainhtml静态
2条回答

我不知道为什么会这样,但在尝试了无数次之后,这就是解决问题的方法。如果有人知道为什么,请开导我。在

  • 我更改了config字典,使其拥有所有global变量 在小词典下。在
  • 我去掉了cherrypy.config.update()函数,并将配置直接输入cherrypy.quickstart()

以下是更改后的代码:

import sys
import cherrypy
import os
from Cheetah.Template import Template

class Root:
    @cherrypy.expose
    def index(self):
        htmlTemplate = Template(file='templates/index.tmpl')
        htmlTemplate.css_scripts=['static/css/main.css']
        return str(htmlTemplate)

# On Startup
current_dir = os.path.dirname(os.path.abspath(__file__)) + os.path.sep
config = {
    'global': {
        'environment': 'production',
        'log.screen': True,
        'server.socket_host': '127.0.0.1',
        'server.socket_port': 2000,
        'engine.autoreload_on': True,
        'log.error_file': os.path.join(current_dir, 'errors.log'),
        'log.access_file': os.path.join(current_dir, 'access.log'),
    },
    '/':{
        'tools.staticdir.root' : current_dir,
    },
    '/static':{
        'tools.staticdir.on' : True,
        'tools.staticdir.dir' : 'static',
    },
}
cherrypy.quickstart(Root(), '/', config)

不要把绝对路径放到CSS脚本中,它应该是相对的。在

尝试将其设置为href="/static/css/main.css",并将配置设置为

[/static]
tools.staticdir.on = True
tools.staticdir.dir = 'static'

相关问题 更多 >