roi*_*ere 8 utf-8 httpserver python-3.x
我在使用 BaseHTTPRequestHandler 在 python3 中提供简单网页时遇到编码问题。
这是一个工作示例:
#!/usr/bin/python3
# -*- coding: utf-8 -*
from http.server import BaseHTTPRequestHandler, HTTPServer
from os import curdir, sep, remove
import cgi
HTML_FILE_NAME = 'test.html'
PORT_NUMBER = 8080
# This class will handles any incoming request from the browser
class myHandler(BaseHTTPRequestHandler):
# Handler for the GET requests
def do_GET(self):
self.path = HTML_FILE_NAME
try:
with open(curdir + sep + self.path, 'r') as f:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes(f.read(), 'UTF-8'))
return
except IOError:
self.send_error(404, 'File Not Found: %s' % self.path)
try:
# Create a web server and define the handler to manage the incoming request
with open(HTML_FILE_NAME, 'w') as f:
f.write('<!DOCTYPE html><html><body> <p> My name is Jérôme </p> </body></html>')
print('Started httpserver on port %i.' % PORT_NUMBER)
#Wait forever for incoming http requests
HTTPServer(('', PORT_NUMBER), myHandler).serve_forever()
except KeyboardInterrupt:
print('Interrupted by the user - shutting down the web server.')
server.socket.close()
remove(HTML_FILE_NAME)
Run Code Online (Sandbox Code Playgroud)
预期结果是提供显示My name is Jérôme的网页。
相反,我有:我的名字是 Jéréme
如您所见,html 页面已正确编码,带有self.wfile.write(bytes(f.read(), 'UTF-8'))
,因此我认为问题来自 Web 服务器。
如何告诉 Web 服务器以 UTF-8 提供页面?
您的 Web 服务器已经在发送编码为 UTF-8 的文本,但您需要告诉浏览器它接收到的字节的编码。HTTP 规范。将 ISO-8995-1 声明为默认值。
HTTP 的标准做法是Content-type
用charset
子键标记标头值。
因此,您应该将代码更改为:
self.send_header('Content-type', 'text/html; charset=utf-8')
Run Code Online (Sandbox Code Playgroud)
另外,请注意 HTML 文件的编码。如果没有提供给open()
的编码,它将根据您的语言环境进行猜测。除非你最终运行此脚本,该区域是这不会破坏任何东西,C
,POSIX
或者非拉丁窗口。
如果我添加没问题:
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
Run Code Online (Sandbox Code Playgroud)
在我的 html 头中。
归档时间: |
|
查看次数: |
5896 次 |
最近记录: |