Make an http POST request to upload a file using Python urllib/urllib2

前端 未结 3 1866
一整个雨季
一整个雨季 2020-12-13 20:39

I would like to make a POST request to upload a file to a web service (and get response) using Python. For example, I can do the following POST request with curl

3条回答
  •  一向
    一向 (楼主)
    2020-12-13 21:29

    After some digging around, it seems this post solved my problem. It turns out I need to have the multipart encoder setup properly.

    from poster.encode import multipart_encode
    from poster.streaminghttp import register_openers
    import urllib2
    
    register_openers()
    
    with open("style.css", 'r') as f:
        datagen, headers = multipart_encode({"file": f})
        request = urllib2.Request("http://jigsaw.w3.org/css-validator/validator", \
                                  datagen, headers)
        response = urllib2.urlopen(request)
    

提交回复
热议问题