无法在Python 2中设置HTTP CGI服务器

时间:2013-12-17 23:00:24

标签: python python-2.7 cgi

有没有人注意到这一点?

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler


class Handler(CGIHTTPRequestHandler):
    cgi_directories = ["/"]


httpd = HTTPServer(("", 8000), Handler)
httpd.serve_forever()

完整的追溯:

Traceback (most recent call last):
  File "server.py", line 6, in <module>
    from CGIHTTPServer import CGIHTTPRequestHandler
  File "C:\Python27\lib\CGIHTTPServer.py", line 30, in <module>
    import SimpleHTTPServer
  File "C:\Python27\lib\SimpleHTTPServer.py", line 27, in <module>
    class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  File "C:\Python27\lib\SimpleHTTPServer.py", line 208, in SimpleHTTPRequestHan
ler
    mimetypes.init() # try to read system mime.types
  File "C:\Python27\lib\mimetypes.py", line 358, in init
    db.read_windows_registry()
  File "C:\Python27\lib\mimetypes.py", line 258, in read_windows_registry
    for subkeyname in enum_types(hkcr):
  File "C:\Python27\lib\mimetypes.py", line 249, in enum_types
    ctype = ctype.encode(default_encoding) # omit in 3.x!
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 2: ordinal
not in range(128)

我过去常常运行此代码,但它运行正常,但现在却根本没有。该代码在Python 3中完美运行(更改导入)。

在Windows 8上运行Python 2.7.6(均为64位)。重新安装Python不起作用。

有什么想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

解决。这是一个问题,因为mimetypes模块导致Windows注册表中的编码。如果有人在将来发现同样的问题,here是解决它的补丁。如果您不想浪费时间检查,那么这就是快速解决方案。将mimetypes模块(enum_types())中的Lib/mimetypes.py函数替换为此函数:

from itertools import count
def enum_types(mimedb):
    for i in count():
        try:
            yield _winreg.EnumKey(mimedb, i)
        except EnvironmentError:
            break

感谢所有人。