Trying to post multipart form data in python, won&

2020-03-04 04:47发布

问题:

I'm fairly new to python, so I apologize in advance if this is something simple I'm missing. I'm trying to post data to a multipart form in python. The script runs, but it won't post. I'm not sure what I'm doing wrong.

import urllib, urllib2
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

def toqueXF():
    register_openers()
    url = "http://localhost/trunk/admin/new.php"
    values = {'form':open('/test.pdf'),
              'bandingxml':open('/banding.xml'),
              'desc':'description'}
    data, headers = multipart_encode(values)
    request = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(request)
    the_page = response.read()
    print the_page

When I call this, the print gives me the html of the page, as if I ran "urllib2.urlopen(url)" and didn't post any data:

<form enctype="multipart/form-data" action="" method="post">
    <p><input type="hidden" name="MAX_FILE_SIZE" value="1000000000" /></p>
    <p>Select PDF file to create form from: <input name="form" type="file" /></p>
    <p>(Optional): Select banding XML file: <input name="bandingxml" type="file" /></p>
    <p>Enter description of form: <input name="desc" type="text"/><br/></p>
    <p><input type="submit" value="Upload form" /></p>
</form>

poster is to encode the data to multipart/form data and can be found here: http://atlee.ca/software/poster/index.html

I found the code to use poster here: Using MultipartPostHandler to POST form-data with Python

If anyone's curious, I'm trying to automatically post a pdf and xml banding file after they're generated for queXF (an opensource optical mark recognition software). http://quexf.sourceforge.net/

回答1:

import urllib, urllib2
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

def queXF():
    register_openers()
    url = "http://lilix2/trunk/admin/new.php"
    values = {'form':open('test.pdf'),
          'bandingxml':open('banding.xml'),
          'desc':'description'}
    data, headers = multipart_encode(values)
    headers['User-Agent'] = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    request = urllib2.Request(url, data, headers)
    request.unverifiable = True
    response = urllib2.urlopen(request)
    the_page = response.read()

Adding headers['User-Agent'] and request.unverifiable = True seems to have fixed it.



回答2:

Try using the requests library. Docs on posting multipart file are here: http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file