2

I can't find an example of how to set up a http server in python, which saves files to a directory which are sent to it using HTTP POST with urllib2, requests or curl.

I want to use it as part of a program where a client analyses data, and sends the results file back to the server. The server saves the file to a directory where the results are analysed.

Thanks

1

1 Answer 1

1

I did this recently using the CGI module in Python. My POST method and file copy process are below. It uses a form, where sfname is the full path of where the file had to saved and file is the file itself. This is slightly more complex than what you need, but it should get you going.

def do_POST(self):
    f = StringIO()
    fm = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST'})
    if "file" in fm:
        r, resp, info = self.get_file_data(fm)
        print r, info, "by: ", self.client_address
        if r:
            f.write("File upload successful: %s" % info)
            f.seek(0)
            if resp == 200: 
                # Do stuff here
            else:
                # Error handle here
        else:
            f.write("File upload failed: %s" % info)
            f.seek(0)
            if resp == 200: 
                # Do stuff here
            else:
                # Error handle here
        if f:
            copyfileobj(f, self.wfile)
            f.close()
    else:
        # Error handle here

def get_file_data(self, form):
    fn = form.getvalue('sfname')
    fpath, fname = ospath.split(fn)
    if not ospath.isabs(fpath):
        return (False, 400, "Path of filename on server is not absolute")
    if not ospath.isdir(fpath):
        return (False, 400, "Cannot find directory on server to place file")
    try:
        out = open(fn, 'wb')
    except IOError:
        return (False, 400, "Can't write file at destination. Please check permissions.")
    out.write(form['file'].file.read())
    return (True, 200, "%s ownership changed to user %s" % (fn, u))

Also, this were the packages I imported. You might not need all of them.

from shutil import copyfileobj
from os import path as ospath
import cgi,
import cgitb; cgitb.enable(format="text")
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

I tested it with curl -F "file=@./myfile.txt" -F "sfname=/home/user/myfile.txt" http://myserver and it worked fine. Can't guarantee the other methods. Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

can you please upvote or mark as correct? I'm trying to build some rep here... ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.