Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

python-3.x - 如何使用urllib Python3库转换以下代码?(How can I convert the below code using urllib Python3 library?)

Below code works absolutely fine for me when I used python's requests library.

(当我使用python的请求库时,以下代码对我来说绝对正常。)

I want the same action to be done using urllib in Python3 library.

(我希望使用Python3库中的urllib进行相同的操作。)

import requests

files = {'FileData': open(sample.png, 'rb')}
headers={
    "Authorization": "Basic ***********"
}
result = requests.post("https://my_sample_api_url",headers=headers,files=files)

I tried to do this post call in urllib like this, which gives me 400 Bad Request Error.

(我试图这样在urllib中进行此调用,这给了我400错误的请求错误。)

import urllib
from urllib.request import Request, urlopen

files = {'FileData': open("sample.png", "rb")}
headers={
    "Authorization": "Basic ************"
}

data_bytes = urllib.parse.urlencode(files).encode("utf-8")
result_req = Request("https://my_sample_api_url", data=data_bytes, headers=headers)
result = urlopen(image_result_req)

How can I convert this code to urllib?

(如何将该代码转换为urllib?)

  ask by Prathyush P translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To upload files as multipart/form-data you could use urllib along with poster library.

(要将文件作为multipart/form-data上传,您可以将urllib海报库一起使用。)

from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib

# Register the streaming http handlers with urllib
register_openers()

# Start the multipart/form-data encoding of the file "sample.png"

# headers contains the necessary Content-Type and Content-Length
# datagen is a generator object that yields the encoded parameters
datagen, headers = multipart_encode({"image": open("sample.png")})

request = urllib.request.Request("https://my_sample_api_url", datagen, headers)

request.add_header("Authorization", "Basic ***********")

print(urllib.request.urlopen(request).read())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...