python post请求抛出UnicodeEncodeError:'ascii'编解码器无法编码字符u'\ xa0'

Posted

技术标签:

【中文标题】python post请求抛出UnicodeEncodeError:\'ascii\'编解码器无法编码字符u\'\\ xa0\'【英文标题】:python post request throws UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0'python post请求抛出UnicodeEncodeError:'ascii'编解码器无法编码字符u'\ xa0' 【发布时间】:2017-05-30 12:44:48 【问题描述】:

我的 python 代码使用 REST API 从 Confluence 读取页面数据,然后使用该数据在 Confluence 中创建一个新页面。发布数据时,代码抛出以下错误:

 UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 48108: ordinal not in range(128)

但是,它在 Postman 中运行良好。我的猜测是邮递员处理编码。我发现许多建议使用str.encode('utf-8')str.encode('ascii', 'ignore') 的答案,但没有一个对我有用。我也试过了:

   import sys
   reload(sys)
   sys.setdefaultencoding('utf-8')    

但徒劳无功。如果我使用其中任何一个进行编码,则在触发发布请求时会收到 500 内部错误

这是我的 python 代码:get_template_data 获取汇合页面详细信息并在发布请求中使用它来创建新页面。

#5. Get the weekly status template page data
def get_template_data():
    url = 'https://confluence.abc.com/rest/api/content/11111111?expand=body.export_view'
    headers['content-type'] = "application/json"    
    r = requests.get(url, headers=headers)
    data = r.json()
    template_data=data['body']['export_view']['value']
    return template_data

#6. Using weekly status template page(5) & string(2), create (post) a new page in Confluence.
def create_weekly_status_page(title,template_data):
    post_data_prefix = """"type":"page","title":"%s", "ancestors":["id":222222], "space":"key":"TST","body":"storage":"value":"%s","representation":"storage""""

    #template_data1 = u' '.join(template_data).encode('utf-8')
    template_data = template_data.replace('"', '\\"')
    post_body_str = post_data_prefix % (title, template_data)

    url = 'https://confluence.abc.com/rest/api/content/'
    headers['content-type'] = "application/json"

    r = requests.post(url, headers=headers, data=post_body_str)
    print r.status_code
    r.raise_for_status()

def main():
    #5. Get the weekly status template page data
    template_data = get_template_data()
    #print "template_data:", template_data

    #6. Using weekly status template page(5) & string(2), create (post) a new page in Confluence.
    # The weekly status string (2) will serve as title of the page
    weekly_status_str = "Weekly Report (01/01/17 - 01/05/17)
    create_weekly_status_page(weekly_status_str,template_data)

罪魁祸首是r = requests.post(url, headers=headers, data=post_body_str)。所以post_body_str 中的数据很可能与此有关。

以下是stracktrace:

Traceback (most recent call last):
  File "new_status.py", line 216, in <module>
    main()
  File "new_status.py", line 193, in main
    create_weekly_status_page(weekly_status_str,template_data)
  File "new_status.py", line 79, in create_weekly_status_page
    url = 'https://confluence.abc.com/rest/api/content/'
  File "/Library/Python/2.7/site-packages/requests/api.py", line 110, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/api.py", line 56, in request
    return session.request(method=method, url=url, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 488, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 609, in send
    r = adapter.send(request, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/adapters.py", line 423, in send
    timeout=timeout
  File "/Library/Python/2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 594, in urlopen
    chunked=chunked)
  File "/Library/Python/2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 361, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1053, in request
    self._send_request(method, url, body, headers)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1093, in _send_request
    self.endheaders(body)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1049, in endheaders
    self._send_output(message_body)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 897, in _send_output
    self.send(message_body)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 869, in send
    self.sock.sendall(data)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 721, in sendall
    v = self.send(data[count:])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 687, in send
    v = self._sslobj.write(data)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 52926: ordinal not in range(128)

另外,我在获取模板数据时使用body.export_view,因为该页面包含宏,我不希望复制宏,而是复制宏的结果。因此使用body.export_view

我对 Python 很陌生。并编写此代码以自动化一些东西并同时学习 Python。将不胜感激一些帮助/指针。

Python 版本:2.7.10

【问题讨论】:

【参考方案1】:

在这两行的帮助下,我终于设法完成了这项工作:

template_data = template_data.encode('ascii', 'ignore')template_data = template_data.replace('\n', '\\n')

第一行修复UnicodeEncodeError,而第二行修复500 Internal Error

【讨论】:

嗨 Sandeep,你能解释一下你在哪里添加了这两行吗?由于您提到罪魁祸首是您提出的获取请求。我面临着完全相同的错误:(【参考方案2】:

response = requests.get(url = url, headers = headers)

mydata = response.text.encode('ascii', 'ignore')

在浪费了一天的时间后,上面为我解决了这个问题:( :(

【讨论】:

以上是关于python post请求抛出UnicodeEncodeError:'ascii'编解码器无法编码字符u'\ xa0'的主要内容,如果未能解决你的问题,请参考以下文章

JQuery Ajax POST 抛出空错误而不发出请求

使用 POST 方法上传 JSON 对象时抛出错误请求异常

jQuery .ajax() POST 请求抛出 405(不允许的方法)但 GET 不会

Spring security login-processing-url 抛出 405 请求方法 POST 不支持

Laravel 5 App - AJAX Post请求不接受令牌并抛出500内部服务器错误

从 azure 存储中获取文件并通过 Post 方法发送它会抛出错误,但适用于本地文件