TypeError:在Python 3.5.1中无法将字节连接到str

时间:2019-02-18 01:26:09

标签: python-3.x rest api encode concat

即使设置了base64编码,我也遇到了错误:

Traceback (most recent call last):
  File "api_tufin_5.py", line 41, in <module>
    main(sys.argv[1:])
  File "api_tufin_5.py", line 28, in main
    headers['Authorization'] = 'Basic ' + base64.b64encode(user + ':' + 
    password)
TypeError: can't concat bytes to str

这是我的代码:

import requests, sys, base64, collections, json


# global vars
server_ip = 'url'
headers = {}
user = b'username'
password = b'password'
debug = False

def http_get(url, headers=headers):

        try:
                r = requests.get(url=url, headers=headers, verify=False)
        except requests.exceptions.RequestException as e:
                print >> sys.stderr, e
                return

        if debug:
                print (r.text)

        http_result = collections.namedtuple('HTTP_Result', ['status', 
        'text'])
        return http_result(r.status_code, r.text)


def main(argv):
        headers['Accept'] = 'application/json'
        headers['Authorization'] = 'Basic ' + base64.b64encode(user + ':' + 
        password)


        r = http_get('url/securechangeworkflow/api/securechange/tickets?
        status=In Progress&count=10&start=1&expand_links=false')
        if r.status != 200:
                print >> sys.stderr, "Failed to get devices"
                print >> sys.stderr, "Status: ", r.status
                return -1

        print (r.text)


if  __name__ =='__main__':
    main(sys.argv[1:])

为什么在对base64进行编码后仍会显示错误?是什么导致它不将字节连接到str?使用+应该能够将两个字符串合并为一个对象。

0 个答案:

没有答案