[英]Mixing mime types with HTTPServer in python
Right now I have this file structure 现在我有这个文件结构
server-
|
|css-
| |bad.css
|
|html-
| |bad.html
|
|jpg-
| |bad.jpg
|
|server.py
this is bad.css: 这是bad.css:
body
{
background-image:url('bad.jpg');
background-repeat:no-repeat;
background-position:right top;
margin-right:200px;
}
this is bad.html: 这是bad.html:
<html>
<head>
<link rel="stylesheet" type="text/css" href="bad.css">
</head>
<body>
<h1>This isn't a thing!</h1>
<p>You must be mistaken. But <a href="/index">here</a> is where you can find your way again.</p>
</body>
</html>
this is the relevant part of server.py 这是server.py的相关部分
from BaseHTTPServer import BaseHTTPRequestHandler as Handler
from mime types import guess_type
class MyHandler(Handler):
def do_GET(self):
print self.path
print self.headers
extensions = ['html', 'css', 'jpg']
fname = self.path
for ext in extensions:
if fname.endswith(ext):
fname = ext + fname
break
if fname.split('/')[0] == '':
fname = 'html/bad.html'
mimetype = guess_type(fname)[0]
print fname
data = open(fname, 'rb')
self.send_response(200)
self.send_header('Content-type', mimetype)
self.end_headers()
self.wfile.write(data.read())
data.close()
My updated code should have fixed it, but now my browser doesn't render it at all, it just shows html code. 我更新的代码应该已经修复了它,但是现在我的浏览器根本不渲染它,只显示了html代码。
The reason why your css and images won't load is because your handler doesn't know how to handle the request(s) for those files. 您的CSS和图片无法加载的原因是,您的处理程序不知道如何处理这些文件的请求。 Here is a simple example copied (and tweaked abit) from nosklo's answer in the question you linked to. 这是一个简单的示例,它从您链接到的问题的nosklo的答案中复制(并稍作调整)。
def do_GET(self):
try:
if self.path in ("", "/"):
filepath = "html/bad.html"
else:
filepath = self.path.lstrip("/")
f = open(os.path.join('.', filepath), "rb")
except IOError:
self.send_error(404,'File Not Found: %s ' % filepath)
else:
self.send_response(200)
#this part handles the mimetypes for you.
mimetype, _ = mimetypes.guess_type(filepath)
self.send_header('Content-type', mimetype)
self.end_headers()
for s in f:
self.wfile.write(s)
NB: You will have to change the css link in your html from 注意:您必须将html中的css链接从
<link rel="stylesheet" type="text/css" href="../css/bad.css">
to 至
<link rel="stylesheet" type="text/css" href="/css/bad.css">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.