为 urllib.request 添加身份验证信息

add authentication info for urllib.request

我对请求库进行了此查询:

import requests

headers = {
    'Content-type': 'application/json',
}

data = """
{"target": {
  "ref_type": "branch",
  "type": "pipeline_ref_target",
  "ref_name": "main",
  "selector": {
    "type": "branches",
    "pattern" : "main"
    }
  }
}
"""

response = requests.post('https://api.bitbucket.org/2.0/repositories/name/{567899876}/pipelines/', headers=headers, data=data, auth=(username, password))
print(response.text)

现在,我想用 urllib.request 或 urllib3 做同样的事情。我在尝试这个:

from urllib import request, parse

req =  request.Request('https://api.bitbucket.org/2.0/repositories/name/{4567898758}/pipelines/', method="POST", headers=headers, data=data, auth=(username, password))

resp = request.urlopen(req)
print(resp)

但是 urllib 没有 auth参数。我在网上看到了其他例子。例如:

auth_handler = url.HTTPBasicAuthHandler()
auth_handler.add_password(realm='Connect2Field API',
                          uri=urlp,
                          user='*****',
                          passwd='*****')

但我不确定如何将它与我现有的 headers 合并,以便将我的 request 代码转换为 urllib.request 代码。

为了能够使用 urllib 进行身份验证,您需要使用 base64 库对您的凭据进行编码并将其添加为您请求的 header。

from urllib import request, parse
import base64

req =  request.Request('https://api.bitbucket.org/2.0/repositories/name/{4567898758}/pipelines/', method="POST", headers=headers, data=data)

base64string = base64.b64encode(bytes('{}:{}'.format(username, password), 'ascii'))
req.add_header('Authorization', 'Basic {}'.format(base64string.decode('utf-8')))

resp = request.urlopen(req)

编辑:

使用 urllib3 你可以做这样的事情

import urllib3

http = urllib3.PoolManager()
headers = urllib3.make_headers(basic_auth='{}:{}'.format(username, password))
resp = http.urlopen('POST', 'https://api.bitbucket.org/2.0/repositories/name/{4567898758}/pipelines/', headers=headers, data=data)