need help to upload file to webserver

Sells, Fred fred.sells at adventistcare.org
Tue Apr 8 14:16:44 EDT 2008


I am automating the client side of a simple web interface.  I need to upload a file to a webserver that requires authentication.  I've got the authentication working with urllib2 (see below), but the only examples I've found to upload files use httplib without authentication.  I'm competent with Python but no whiz with web api's.  Could I get a little help please.

---------the form I'm trying to simulate looks like this----------------------
<FORM action=/cgi/upload.exe method=post encType=multipart/form-data>
<INPUT type=file name=file></P>
<INPUT type=submit value=Send>
</FORM>
 
------------------my code follows---------------------------------------------
import urllib2, urllib, socket, base64, cookielib
import webtools # from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
STANDARD_HEADERS = {'User-agent':'Mozilla/5.0 (compatible; MSIE 5.5; Windows NT)'}
COOKIEFILE = 'cokies.lwp'
socket.setdefaulttimeout(30)

HTTP = "http://"
HTTPS = "https://"
#IP, UNAME, PW = "............." #deleted for security
top_level_url = "http://..............."


PasswordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()
PasswordManager.add_password(None, top_level_url, UNAME, PW)
AuthenticationHandler = urllib2.HTTPBasicAuthHandler(PasswordManager)
opener = urllib2.build_opener(AuthenticationHandler)
urllib2.install_opener(opener)


class MyConnection:
    def __init__(self, ipaddr="192.168.1.0", uname=None, password=None):
        self.SERVER_AND_PORT = "%s:81" % ipaddr
        self.UNAME = uname
        
        
    def getPage(self, url, kwargs, headers=None):
        headers = headers or STANDARD_HEADERS
        request = urllib2.Request(url, urllib.urlencode(kwargs), headers)
        handle = urllib2.urlopen(request)
        page = handle.read()
        handle.close()
        return  page
    
    def getValidationReportsPage(self):  ########this works
        self.getPage(HTTPS+self.SERVER_AND_PORT+"/cgi/listrpts.exe",{})
        
    def login(self): #########this works
        try:            print self.getPage(HTTPS+self.SERVER_AND_PORT+"/cgi/mainhtml.exe",{})
        except:         print 'login failed'
            
    def uploadFile(self, filepath):  #????????????? need help here
        buffer = open(filepath).read()
        headers = dict(STANDARD_HEADERS)  #make a copy
        parms = ('file', filepath, buffer )
        contenttype, body = webtools.encode_multipart_formdata([], [parms])
        headers['Content-Type']= contenttype
        data = {'file':body}
        self.getPage(HTTPS+self.SERVER_AND_PORT+"/cgi/upload.exe",data,headers)
       
          
        
def unittest():
    print 'start unittest of '+ __file__
    X = MyConnection(uname=UNAME, password=PW)
    X.login()
    X.uploadFile('testdata/MouseMds.txt')
          
if __name__ == "__main__":
    unittest()
            
 


--------------------------------------------------------------------------------
You rock. That's why Blockbuster's offering you one month of Blockbuster Total Access, No Cost. 

---------------------------------------------------------------------------
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---------------------------------------------------------------------------



More information about the Python-list mailing list