У меня проблемы с кодированием при обслуживании простой веб-страницы в python3 с использованием BaseHTTPRequestHandler.python3: кодировка UTF-8 в http.server
Вот рабочий пример:
#!/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)
Ожидаемый результат должен служить веб-страница отображения Меня зовут Жером.
Вместо этого, у меня есть: Меня зовут JÃ © rÃ'me
Как вы можете видеть, страница HTML правильно кодируются с self.wfile.write(bytes(f.read(), 'UTF-8'))
, так что я думаю, что проблема исходит от веб-сервера.
Как сообщить веб-серверу, чтобы он обслуживал страницу в UTF-8?