quick search:
 

Upload a file to Zope from Python using http (no dtml)

Submitted by: pieterb2
Last Edited: 2004-10-14

Category: Python(Script)

Average rating is: 5.0 out of 5 (2 ratings)

Description:
I wanted to add a local file to Zope.
This script uses manage_addFile to sent the file (test.jpg) over to Zope over http. Tested with Zope 2.6a1 and Python 2.1.3 but it should work with other Zope based on Python 2.1 as well.




Source (Text):
# uploadfile.py
# this python script uploads a local file to Zope over http
# thanx to VladDrac / www.amaze.nl for helping me out with 
# the authentication

# todo:
# - fix: hangs if userid/password is wrong
# - check if file is uploaded succesfully
# - use mimelib to encode the file (instead of using urlencode)

import urllib

# fill these in
user='xxx'
password='yyy'
addfileurl='http://yourzopehost/some/dir/manage_addFile'
useragent="uploadfile.py/0.1"
filename='test.jpg'
filetitle='a nice test picture'

class MyUrlOpener(urllib.FancyURLopener):
    def prompt_user_passwd(self, host, realm):
         return (user,password)
    def __init__(self, *args):
       self.version = useragent
       urllib.FancyURLopener.__init__(self, *args)

def main():
        # use authentication and set the user agent
        urllib._urlopener = MyUrlOpener()

        # read the contents of filename into filebody
        f=open(filename)
        filebody=f.read()
        f.close

        # urlencode the id, title and file
        params = urllib.urlencode({'id': filename,
        'title':filetitle,
        'file':filebody})

        # send the file to zope
        f=urllib.urlopen(addfileurl, params)

if __name__ == '__main__':
    main()

Explanation:
Related:

"Upload a File or Image (DTML)":http://www.zopelabs.com/cookbook/1006887320
"How to create a form to upload a file and then access this file from Zope":http://www.zope.org/Members/Benno/FileUpload

Thanks to VladDrac / "Amaze":http://www.amaze.nl/ for helping me out with the authentication.</p>

Please sent me comments to improve this recipe, "PieterB":http://www.zwiki.org/PieterB


Comments:

Why can't I add URL's? by pieterb2 - 2004-10-14
Why aren't URL's supported (either expanded, or using html-code or structured text)


Binary file problem by peenNOR - 2006-03-07
Remember to open the file in binary, else some/most files will not be properly uploaded.

Fix: 

was: f=open(filename)
should be: f=open(filename, 'rb')

 
script not working on windows by riffenstein - 2006-03-07
i am using your script to upload images to my local zope through a python application. This application is built for Windows. 
When I test the script on Linux, it works perfectly. However, when i try to run this same script on Windows,
it doesnt upload the image. I am getting no errors/tracebacks that I could paste over here. anything im missing here?