首页 > 解决方案 > POST 数据应该是字节、字节的可迭代对象或文件对象。它不能是 str 类型

问题描述

我正在尝试将工作 Python 2.7 代码转换为 Python 3 代码,但收到以下错误。请指教。

蟒蛇2.7

import sys, urllib2, json, tower_cli, os, datetime, base64
req = urllib2.Request(url = 'http://test/api/v2/job_templates/23/launch/')
base64string = base64.encodestring('%s:%s' % ('app-splunkansiblenp', 'yCXIxn0#grkuVsL$RTI9!')).replace('\n', '')
req.add_header("Authorization", "Basic %s" % base64string)
response = urllib2.urlopen(req)
print "Response code was: %d" % response.getcode()

使用python转换器工具转换为3.0

蟒蛇 3

import sys, urllib.request, urllib.error, urllib.parse, json, tower_cli, os, datetime, base64
req = urllib2.Request(url = 'http://test/api/v2/job_templates/23/launch/')
base64string = base64.encodestring(('%s:%s' % ('app-splunkansiblenp', 'yCXIxn0#grkuVsL$RTI9!')).encode()).decode().strip()
req.add_header("Authorization", "Basic %s" % base64string)
response = urllib.request.urlopen(req)
print("Response code was: %d" % response.getcode())

我可以在命令提示符下使用上面的代码成功连接到 ansible url,但是当 Splunk 使用上面的代码连接到 ansible 时失败并出现以下错误。请指教。

 ERROR sendmodalert - action=tower_api STDERR - Traceback (most recent call last):
 ERROR sendmodalert - action=tower_api STDERR - File "/opt/splunk/etc/apps/alert_ansible_tower/bin/tower_api.py", line 126, in <module>
 ERROR sendmodalert - action=tower_api STDERR - main(payload)
 ERROR sendmodalert - action=tower_api STDERR - File "/opt/splunk/etc/apps/alert_ansible_tower/bin/tower_api.py", line 112, in main
 ERROR sendmodalert - action=tower_api STDERR - tower_launch(hostname,username,password,job_id,extra_vars)
 ERROR sendmodalert - action=tower_api STDERR - File "/opt/splunk/etc/apps/alert_ansible_tower/bin/tower_api.py", line 70, in tower_launch
 ERROR sendmodalert - action=tower_api STDERR - response = urllib.request.urlopen(req)
 ERROR sendmodalert - action=tower_api STDERR - File "/opt/splunk/lib/python3.7/urllib/request.py", line 222, in urlopen
 ERROR sendmodalert - action=tower_api STDERR - return opener.open(url, data, timeout)
 ERROR sendmodalert - action=tower_api STDERR - File "/opt/splunk/lib/python3.7/urllib/request.py", line 523, in open
 ERROR sendmodalert - action=tower_api STDERR - req = meth(req)
 ERROR sendmodalert - action=tower_api STDERR - File "/opt/splunk/lib/python3.7/urllib/request.py", line 1280, in do_request_
 ERROR sendmodalert - action=tower_api STDERR - raise TypeError(msg)
 ERROR sendmodalert - action=tower_api STDERR - TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.
 INFO sendmodalert - action=tower_api - Alert action script completed in duration=333 ms with exit code=1

标签: python

解决方案


推荐阅读