[英]"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
這完全是因為 WSGI 是為 Python 2 制作的,因此在 Python 3 中使用它可能會遇到一些麻煩。如果您不想像第一個答案那樣更改庫的行為,解決方法是encode()
所有文本數據,例如:
def application(environ,start_response):
response_body = 'Hello World'
return [response_body.encode()]
在“handlers.py”第 180 行
self.write(data.encode())
而不是self.write(data)
Wsgi 框架是圍繞 Python 2 構建的。因此,如果您的程序中有不包含 Python 3 依賴項的內容,請使用 Python 2 運行該應用程序。
就我而言,問題原來是我無意中輸出了一個對象而不是字符串。 通過json.dumps(obj)
將我的結果編碼為字符串來修復。
+++ 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.