如何在CouchDB中存储os.urandom(8)的输出?

时间:2012-02-28 18:14:03

标签: python couchdb couchdb-python

我正在尝试在couchdb中存储一些加密数据。我需要在couchdb中存储salt和加密密码。 salt是使用python的os.urandom(8)生成的,其示例输出如下:

'z/\xfe\xdf\xdeJ=y'

我正在使用python-couchdb api来存储文档。当我尝试保存文档时,我得到:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "build/bdist.macosx-10.7-intel/egg/couchdb/client.py", line 343, in __setitem__
    status, headers, data = resource.put_json(body=content)
  File "build/bdist.macosx-10.7-intel/egg/couchdb/http.py", line 499, in put_json
    **params)
  File "build/bdist.macosx-10.7-intel/egg/couchdb/http.py", line 514, in _request_json
    headers=headers, **params)
  File "build/bdist.macosx-10.7-intel/egg/couchdb/http.py", line 510, in _request
    credentials=self.credentials)
  File "build/bdist.macosx-10.7-intel/egg/couchdb/http.py", line 260, in request
    body = json.encode(body).encode('utf-8')
  File "build/bdist.macosx-10.7-intel/egg/couchdb/json.py", line 68, in encode
    return _encode(obj)
  File "build/bdist.macosx-10.7-intel/egg/couchdb/json.py", line 129, in <lambda>
    dumps(obj, allow_nan=False, ensure_ascii=False)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 204, in encode
    return ''.join(chunks)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xfe in position 3: ordinal not in range(128)

2 个答案:

答案 0 :(得分:1)

在保存之前将其编码为base64或十六进制,或将其保存在二进制字段中。

答案 1 :(得分:0)

将基数为64的urandom输出编码为:

os.urandom(8).encode('base64')

根据此thread

中的示例