自定义WSGI服务器运行提示编码错误,实在不知道怎么解决,只能找大佬帮忙

自定义WSGI服务器运行提示编码错误,实在不知道怎么解决,只能找大佬帮忙

import json
from wsgiref.simple_server import make_server


def demo_app(environ, start_response):
    path = environ['PATH_INFO']
    status_code = '200 ok'
    if path == '/':
        response = '欢迎来到我的首页'
    elif path == '/test':
        response = json.dumps({'name': 'zhangsan', 'age': '18'})
    elif path == '/demo':
        response = '欢迎来到demo页面'
    else:
        status_code = '404 Not Found'
        response = '页面走丢了'

    start_response(status_code, [('Content-Type', 'text/html;charset=utf8')])
    return [response.encode('utf8')]  # 浏览器显示的内容


if __name__ == '__main__':
    httpd = make_server('', 8000, demo_app)
    sa = httpd.socket.getsockname()
    print("Serving HTTP on", sa[0], "port", sa[1], "...")
    import webbrowser

    webbrowser.open('http://localhost:8000/xyz?abc')
    httpd.serve_forever()


    下面是运行后提示的错误

Traceback (most recent call last):
  File "D:/python_cord/网络编程/HTTP服务器搭建/wsgl服务器.py", line 24, in <module>
    httpd = make_server('', 8000, demo_app)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\wsgiref\simple_server.py", line 153, in make_server
    server = server_class((host, port), handler_class)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\socketserver.py", line 452, in __init__
    self.server_bind()
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\wsgiref\simple_server.py", line 50, in server_bind
    HTTPServer.server_bind(self)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\http\server.py", line 139, in server_bind
    self.server_name = socket.getfqdn(host)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\socket.py", line 676, in getfqdn
    hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 4: invalid start byte

```

讨论数量: 2
pardon110

代码编辑器的编码格式非utf8

3年前 评论
Jason990420

If your computer name has non-ASCII characters this will fail.

Check it by

d:\>hostname
3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!