强制转换为Unicode:需要字符串或缓冲区,找到列表

时间:2014-10-07 13:54:40

标签: python django django-rest-framework

我有一个django rest框架视图,其中包含以下代码 -

trgmst_info = request.DATA['trgmst_info'][0]
request_accts = ['request-dev', 'request-qa', 'request-uat', 'request-prod']
request.DATA['trgmst_info'] = [rd.replace(request_accts, settings.REQUEST_ACCT) for rd in request.DATA['trgmst_info']]

request.DATA [' trgmst_info'] [0]的值如下 -

"<eventmon><conn>24</conn><action>3</action><folder/><mailbox>Inbox</mailbox><condition><condcount>1</condcount><criteria1>Sender</criteria1><ctext1>test_MESSage</ctext1><csensitive1>Y</csensitive1></condition><msgbody>Y</msgbody><evtmtrg>Inbox (request-dev@mailserver.blah.com)</evtmtrg></eventmon>"

我尝试做的是扫描其中一个request_accts并将其替换为settings在设置中的值.REQUEST_ACCT

所有发生的事情仍然是以下错误 -

coercing to Unicode: need string or buffer, list found

Traceback:
File "D:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Python27\lib\site-packages\django\views\generic\base.py" in view
  69.             return self.dispatch(request, *args, **kwargs)
File "D:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  57.         return view_func(*args, **kwargs)
File "D:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
  400.             response = self.handle_exception(exc)
File "D:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
  397.             response = handler(request, *args, **kwargs)
File "D:\Tidal\API\views.py" in put
  464.                 request.DATA['trgmst_info'] = [rd.replace(request_accts, settings.REQUEST_ACCT) for rd in request.DATA['trgmst_info']]

Exception Type: TypeError at /deploy/event/
Exception Value: coercing to Unicode: need string or buffer, list found

编辑 - 如果我在第一行后隐藏以下代码 -

print trgmst_info

返回<。如果我将第一行更改为以下内容 -

trgmst_info = request.DATA['trgmst_info']

打印返回所有内容 -

<eventmon><conn>24</conn><action>3</action><folder/><mailbox>Inbox</mailbox><condition><condcount>1</condcount><criteria1>Sender</criteria1><ctext1>test_MESSage</ctext1><csensitive1>Y</csensitive1></condition><msgbody>Y</msgbody><evtmtrg>Inbox (request-dev@mailserver.blah.com)</evtmtrg></eventmon>

但同样的错误仍然存​​在。

1 个答案:

答案 0 :(得分:1)

string.replace()使用字符串作为参数而不是列表。 request_accts 是一个清单。

我不是django专家,但也许这会奏效:

trgmst_info = request.DATA['trgmst_info'][0]
request_accts = ['request-dev', 'request-qa', 'request-uat', 'request-prod']
for rep in request_accts:
    request.DATA['trgmst_info'] = [rd.replace(rep, settings.REQUEST_ACCT) for rd in request.DATA['trgmst_info']]