How do I post a file over HTTP using the standard

2019-05-08 09:25发布

问题:

I am currently using PycURL to trigger a build in Jenkins, by posting to a certain URL. The relevant code looks as follows:

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

As you can see, one of the post parameters ('file0') is a file, as indicated by the parameter type pycurl.FORM_FILE.

How can I replace my usage of PycURL with the standard Python library?

回答1:

Standard python library has no support of multipart/form-data that required for post files through POST requests.

There is some recipes eg http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/



回答2:

u = urllib.urlopen(url, data=urllib.urlencode(
                             {'name': 'CI_VERSION', 
                              'value': str(version),
                              'file0': open(metadata_fpath).read(),
                               etc. 
                               etc.})) 

You can do this with urllib / urllib2. Above is a minimal example of sending a POST request.