我想显示这个字符"(U+203E)",但这是我在本地主机上得到的:â
from http.server import HTTPServer, BaseHTTPRequestHandler
class Serv(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = '/file.txt'
try:
file_to_open = open(self.path[1:]).read()
self.send_response(200)
except:
file_to_open = "File not found"
self.send_response(404)
self.end_headers()
self.wfile.write(bytes(file_to_open, 'utf-8'))
httpd = HTTPServer(('localhost', 8080), Serv)
httpd.serve_forever()
file.txt:
‾
本地显示:
‾
如何正确显示Unicode字符?
据我所知,浏览器不必使用utf-8
作为默认编码,而是使用iso8859-2
。
浏览器不知道文件里面的编码是什么,你必须使用HTTP头来通知它
self.send_header("Content-Type", "text/plain; charset=utf-8")
最小工作示例
from http.server import HTTPServer, BaseHTTPRequestHandler
class Serv(BaseHTTPRequestHandler):
def do_GET(self):
text = '‾'
self.send_response(200)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.end_headers()
#self.wfile.write(bytes(text, 'utf-8'))
self.wfile.write(text.encode('utf-8'))
print('Serving http://localhost:8080')
httpd = HTTPServer(('localhost', 8080), Serv)
httpd.serve_forever()
编辑:
如果你要用HTML发送文件,那么在文件中你可以使用HTML标签
<meta charset="utf-8">
最小工作示例
from http.server import HTTPServer, BaseHTTPRequestHandler
class Serv(BaseHTTPRequestHandler):
def do_GET(self):
text = '''<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
‾
</body>
</html>
'''
self.send_response(200)
self.end_headers()
#self.wfile.write(bytes(text, 'utf-8'))
self.wfile.write(text.encode('utf-8'))
print('Serving http://localhost:8080')
httpd = HTTPServer(('localhost', 8080), Serv)
httpd.serve_forever()