为什么我在浏览器中转到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;}
WSGI只为你Python代码提供服务,甚至可能不知道那个CSS文件的存在。
您可以将 Web 服务器配置为为您处理静态资产,也可以使用 static 之类的东西来提供静态媒体。
您尝试通过 wsgi 服务器加载 css,但您的服务器始终只返回 html 文件。看看萤火虫/网络检查器/...以查看服务器对 CSS 文件的响应。
代码片段仅用于学习目的。我创建了一个静态目录并将我的索引.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()
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()