"AssertionError: write() argument must be a bytes instance" when running WSGISOAPHandler

"AssertionError: write() argument must be a bytes instance" when running WSGISOAPHandler

我在 Python 3.

中有一个带有 pysimplesoap 的 SOAP 服务器

代码

from wsgiref.simple_server import make_server

application = WSGISOAPHandler(dispatcher)
wsgid = make_server('', 8008, application)
wsgid.serve_forever()

我不知道为什么会出现以下错误。

错误

Traceback (most recent call last):
  File "/usr/lib/python3.4/wsgiref/handlers.py", line 138, in run
    self.finish_response()
  File "/usr/lib/python3.4/wsgiref/handlers.py", line 180, in finish_response
    self.write(data)
  File "/usr/lib/python3.4/wsgiref/handlers.py", line 266, in write
    "write() argument must be a bytes instance"
AssertionError: write() argument must be a bytes instance
+++ pysimplesoap/server.py  

                     e['name'] = k
                     if array:
                         e[:] = {'minOccurs': "0", 'maxOccurs': "unbounded"}
-                    if v in TYPE_MAP.keys():
-                        t = 'xsd:%s' % TYPE_MAP[v]
-                    elif v is None:
+
+                    # check list and dict first to avoid
+                    # TypeError: unhashable type: 'list' or
+                    # TypeError: unhashable type: 'dict'
+                    if v is None:
                         t = 'xsd:anyType'
                     elif isinstance(v, list):
                         n = "ArrayOf%s%s" % (name, k)
                         n = "%s%s" % (name, k)
                         parse_element(n, v.items(), complex=True)
                         t = "tns:%s" % n
+                    elif v in TYPE_MAP.keys():
+                        t = 'xsd:%s' % TYPE_MAP[v]
                     else:
                         raise TypeError("unknonw type v for marshalling" % str(v))
                     e.add_attribute('type', t)

在“handlers.py”第 180 行

self.write(data.encode()) 而不是 self.write(data)

这都是因为 WSGI 是为 Python 2 制作的,所以您在 Python 3 中使用它可能会遇到一些麻烦。如果您不想像第一个答案那样更改库的行为,解决方法是 encode() 所有文本数据,如:

def application(environ,start_response):
    response_body = 'Hello World'
    return [response_body.encode()]

Wsgi 框架是围绕 Python 2 构建的。因此,如果您的程序中有不包含 Python 3 依赖项的内容,运行 具有 [=12= 的应用程序] 2.

在我的例子中,问题原来是我无意中输出了一个对象而不是一个字符串。通过 json.dumps(obj).

将我的结果编码为字符串来修复