【问题标题】:How can I convert the below code using urllib Python3 library?如何使用 urllib Python3 库转换以下代码?
【发布时间】:2019-11-26 12:07:12
【问题描述】:

当我使用 python 的 requests 库时,下面的代码对我来说工作得很好。我希望在 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)

我尝试像这样在 urllib 中执行此帖子调用,这给了我 400 Bad Request Error。

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)

如何将此代码转换为 urllib?

【问题讨论】:

    标签: python-3.x api urllib


    【解决方案1】:

    要将文件上传为multipart/form-data,您可以使用urllibposter 库。

    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())
    

    【讨论】:

    • 感谢您的快速回复@Harish Vutukuri,非常感谢,但我只想使用 python 标准库而不是任何第三方库,如海报或请求。 (很抱歉在我的问题中没有提到这一点)。
    • 添加到这个@Harish Vutukuri,我尝试使用海报,但 pip3 install poster 给了我语法错误。我猜它只支持python2而不支持python3
    • requests 是最简单的方法,它内置了对多部分后期处理的支持。我相信如果没有任何第三方进口,这是无法实现的。
    • 嗯...但问题是我正在从 AWS lambda 运行我的 python 脚本,我不想在 Lambda 中导入任何第三方。 Requests 对我来说是一个选项,但是“来自 botocore.vendored 导入请求”给出了一个警告,说来自 botocore 的请求库正在被弃用。如果有人可以为此提供更好的解决方案,我将不胜感激。
    • @PrathyushP 你能试一试吗:stackoverflow.com/a/16574609
    猜你喜欢
    • 1970-01-01
    • 2015-09-01
    • 2019-06-26
    • 2021-07-10
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 2021-08-24
    相关资源
    最近更新 更多