一个简单的带有python的wsgi网站,但是没有加载.css文件。为什么?

2024-10-01 15:32:00 发布

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

为什么我在浏览器中转到localhost:8080时背景不是蓝色的? 以下3个文件都位于同一目录中:

在wsgiwebsite.py在

#!/usr/bin/env python
from wsgiref.simple_server import make_server

cont = (open('wsgiwebsite_content.html').read())

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return [cont]

server = make_server('0.0.0.0', 8080, application)
server.serve_forever()

WSGI网站_内容.html在

^{pr2}$

WSGI网站_样式.css在

body{background-color:blue;}

Tags: 文件localhostwsgimakeserverapplication网站response
3条回答

下面的代码片段仅供学习之用。我创建了一个静态目录并保存了索引.html和css文件在那里,因此我自己的源代码文件是不可访问的。在

from wsgiref.simple_server import make_server                                    
import os                                                                        


def content_type(path):                                                          
if path.endswith(".css"):                                                    
    return "text/css"                                                        
else:                                                                        
    return "text/html"                                                       


def app(environ, start_response):                                                
    path_info = environ["PATH_INFO"]                                             
    resource = path_info.split("/")[1]                                           

    headers = []                                                                 
    headers.append(("Content-Type", content_type(resource)))                     

    if not resource:                                                             
        resource = "index.html"                                                  

    resp_file = os.path.join("static", resource)                                 

    try:                                                                         
        with open(resp_file, "r") as f:                                          
            resp_file = f.read()                                                 
    except Exception:                                                            
        start_response("404 Not Found", headers)                                 
        return ["404 Not Found"]                                                 

    start_response("200 OK", headers)                                            
    return [resp_file]                                                           

s = make_server("0.0.0.0", 8080, app)                                            
s.serve_forever()                                              

WSGI只为Python代码提供服务,可能甚至不知道CSS文件的存在。在

您可以将web服务器配置为处理静态资产,也可以使用类似于static的方式为静态媒体提供服务。在

您试图通过wsgi服务器加载css,但是服务器总是返回html文件。看看firebug/web inspector/。。。查看服务器对css文件的响应。在

相关问题 更多 >

    热门问题