utf-8 python3_python-3.x – python3:http.server中的UTF-8编码

使用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('

My name is Jérôme

')

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的网页.

相反,我有:我的名字是JérÃ’me

如您所见,html页面已正确编码,使用self.wfile.write(bytes(f.read(),’UTF-8′)),因此我认为问题来自Web服务器.

如何告诉Web服务器以UTF-8提供页面?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值