如何使用标准Python库通过HTTP发布文件

我目前正在使用PycURL通过发布到某个URL来触发Jenkins的构建.相关代码如下:

curl = pycurl.Curl()
curl.setopt(pycurl.URL, url)
# These are the form fields expected by Jenkins
data = [
        ("name", "CI_VERSION"),
        ("value", str(version)),
        ("name", "integration.xml"),
        ("file0", (pycurl.FORM_FILE, metadata_fpath)),
        ("json", "{{'parameter': [{{'name': 'CI_VERSION', 'value':"
            "'{0}'}}, {{'name': 'integration.xml', 'file': 'file0'}}]}}".
                format(version,)),
        ("Submit", "Build"),
        ]
curl.setopt(pycurl.HTTPPOST, data)
curl.perform()

如您所见,其中一个post参数(‘file0’)是一个文件,如参数类型pycurl.FORM_FILE所示.

如何用标准Python库替换我对PycURL的使用?

最佳答案 标准python库不支持通过POST请求发布文件所需的multipart / form-data.

有一些食谱,例如http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/

点赞