How do I post a file over HTTP using the standard Python library

北慕城南 提交于 2019-12-07 09:19:47

问题


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.



来源:https://stackoverflow.com/questions/7064180/how-do-i-post-a-file-over-http-using-the-standard-python-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!