当我在浏览器中转到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()
wsgiwebsite_content.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="wsgiwebsite_style.css">
</head>
<body>
This is my first web page
</body>
</html>
wsgiwebsite_style.css
body{background-color:blue;}
答案 0 :(得分:1)
您尝试通过wsgi服务器加载css,但您的服务器始终只返回html文件。看看firebug / web inspector / ...来查看服务器对css文件的响应。
答案 1 :(得分:1)
WSGI只提供您的Python代码,甚至可能不知道该CSS文件的存在。
您可以将您的网络服务器配置为为您处理静态资产,或者使用static之类的内容来提供静态媒体。
答案 2 :(得分:1)
以下代码段仅供学习之用。我创建了一个静态目录并在那里保存了我的index.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()
答案 3 :(得分:0)
Denis代码几乎可以解决我的问题,但是我需要进行一些更改/修复,这就是我的工作方式:
from wsgiref.simple_server import make_server
from cgi import parse_qs, escape
import codecs
def tipoDeConteudo(path):
if path.endswith(".css"):
return "text/css"
else:
return "text/html"
def web_app(environment, response):
caminho = environment["PATH_INFO"]
resource = caminho.split("/")[1]
headers = []
headers.append(("Content-Type", tipoDeConteudo(resource)))
try:
resp_file = codecs.open("indexResposta.html", 'r').read()
except Exception:
response("404 Not Found", headers)
return ["404 Not Found"]
response('200 OK', headers)
return [resp_file.encode()]
s = make_server("0.0.0.0", 8080, app)
s.serve_forever()