html消息的编码已损坏



我正在构建一个简单的服务器,它响应GET请求并发送包含utf-8值表的html。该表是使用pandas DataFrame和to_html方法从json对象创建的

服务器基于BaseHTTPRequestHandler类(http.server模块(

当我从Chrome浏览器发送GET请求时,我会收到胡言乱语的文本值

我尝试使用将字符集标签添加到标题中

self.send_header('Content-type', 'text/html; charset=utf-8')
or
self.send_header('charset','utf-8')

我的代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import json
import requests
from http.server import HTTPServer, BaseHTTPRequestHandler
from sys import argv
BIND_HOST = 'localhost'
PORT_HOST = 8000
input = {0: {'יעד': 'באר שבע מרכז', 'זמן הגעה': '17:38:00', 'רציף': '1'}, 1: {'יעד': 'ראש העין צפון', 'זמן הגעה': '17:48:00', 'רציף': '2'}}
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
output = pd.DataFrame(input).transpose().to_html()
print(output)
self.write_response(bytes(output))
except Exception as e:
print(e)
def write_response(self, content):
#      self.send_header('Content-type', 'text/html; charset=utf-8')
#      self.send_header('charset','utf-8')
self.send_response(200)
self.end_headers()
print(content.encode('utf-8'))
self.wfile.write(content.encode(encoding='utf-8'))

if len(argv) > 1:
arg = argv[1].split(':')
BIND_HOST = arg[0]
PORT_HOST = int(arg[1])
httpd = HTTPServer((BIND_HOST, PORT_HOST), SimpleHTTPRequestHandler)
print(f'Listening on http://{BIND_HOST}:{PORT_HOST}n')
httpd.serve_forever()

您需要发送内容类型标头。

# -*- coding: utf-8 -*-
import pandas as pd
import json
import requests
from http.server import HTTPServer, BaseHTTPRequestHandler
from sys import argv
BIND_HOST = 'localhost'
PORT_HOST = 8000
input = {0: {'יעד': 'באר שבע מרכז', 'זמן הגעה': '17:38:00', 'רציף': '1'}, 1: {'יעד': 'ראש העין צפון', 'זמן הגעה': '17:48:00', 'רציף': '2'}}
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
output = pd.DataFrame(input).transpose().to_html()
self.write_response(output.encode('utf-8'))
def write_response(self, content):
self.send_response(200)
self.send_header('Content-type', 'text/html; charset=utf-8')
self.end_headers()
self.wfile.write(content)

if len(argv) > 1:
arg = argv[1].split(':')
BIND_HOST = arg[0]
PORT_HOST = int(arg[1])
httpd = HTTPServer((BIND_HOST, PORT_HOST), SimpleHTTPRequestHandler)
print(f'Listening on http://{BIND_HOST}:{PORT_HOST}n')
httpd.serve_forever()

相关内容

  • 没有找到相关文章

最新更新