运行服务器时的Unicode解码错误

6 投票
3 回答
9223 浏览
提问于 2025-04-18 02:58

在设置好所有 django 需要的东西后,我尝试运行 runserver 命令,但遇到了一个错误:

UnicodeDecodeError: 'utf-8' 编码无法解码位置 8 的字节 0xcf:无效的续字节

来自:

c:\sue>python manage.py runserver
Validating models...

0 errors found
April 16, 2014 - 15:02:42
Django version 1.6.2, using settings 'sue.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000003890048>
Traceback (most recent call last):
  File "C:\python34\lib\site-packages\django\utils\autoreload.py", line 93, in wrapper fn(*args, **kwargs)
  File "C:\python34\lib\site-packages\django\core\management\commands\runserver.py", line 127, in inner_run ipv6=self.use_ipv6, threading=threading)
  File "C:\python34\lib\site-packages\django\core\servers\basehttp.py", line 167, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
  File "C:\python34\lib\site-packages\django\core\servers\basehttp.py", line 109, in __init__ super(WSGIServer, self).__init__(*args, **kwargs)
  File "C:\python34\lib\socketserver.py", line 430, in __init__ self.server_bind()
  File "C:\python34\lib\site-packages\django\core\servers\basehttp.py", line 113, in server_bind super(WSGIServer, self).server_bind()
  File "C:\python34\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self)
  File "C:\python34\lib\http\server.py", line 137, in server_bind
    self.server_name = socket.getfqdn(host)
  File "C:\python34\lib\socket.py", line 460, in getfqdn
    hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 8: invalid continuation byte

我使用的是 Windows 7 x64,python 3.4 和 django 1.6.2。这个错误是什么意思呢?

3 个回答

0

我在使用Python 3.4时遇到了这个问题,情况是这样的:

  • 服务器的主机名只有ASCII字符(比如说 host1
  • /etc/hosts 文件里没有我的主机名的记录
  • 没有可用的DNS解析器(电脑是离线状态)

在我往 /etc/hosts 文件里添加了以下记录后,就没有再出现 UnicodeDecodeError 的错误了。

127.0.0.1 localhost host1
1

我刚遇到这个问题,因为我不小心用https访问了网站,而不是http。切换回http就解决了这个问题。

14

这听起来像是这个Python的问题。如果你的电脑名称包含非ASCII字符(也就是一些特殊字符),这个操作就会失败。你可以尝试以下几种方法:

  1. 使用明确的主机和端口来运行服务器命令:python manage.py runserver 127.0.0.1:8000
  2. 把你的电脑名称改成只包含ASCII字符的字符串。

撰写回答