1

Am a newbie for python and cherrypy. I am trying to upload file using following code:

@cherrypy.tools.noBodyProcess()
def POST(self,theFile=None):
    lcHDRS = {}
    for key, val in cherrypy.request.headers.iteritems():
        lcHDRS[key.lower()] = val
   formFields = myFieldStorage(fp=cherrypy.request.rfile,
                                headers=lcHDRS,
                                environ={'REQUEST_METHOD':'POST'},
                                keep_blank_values=True)

    dt = datetime.now()
    date = dt.strftime('%Y-%m-%d')
    dt = dt.strftime('%Y%m%d%H%M%S')
    theFile = formFields['theFile']
    theFile.filename = str(dt) + "file"
    shutil.copy2(theFile.file.name,os.path.join(absolutePath , theFile.filename))
    ...
    ...

I checked the path os.path.join(absolutePath , theFile.filename) and it is coming proper. The problem is that the code is working fine on Linux-ubuntu, but not on windows. Error invoked is: Edited

shutil.copy2(theFile.file.name,settings.UPLOAD_FILE_PATH + theFile.filename)
File "C:\Anaconda\lib\shutil.py", line 130, in copy2
copyfile(src, dst)
File "C:\Anaconda\lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 13] Permission denied: 'c:\\users\\username\\appdata\\local\\temp\\tmpjy3gys'

Where am i going wrong? If you want any other information please let me know.

zennith
  • 410
  • 2
  • 5
  • 17
  • You provided neither full stack trace of `IOError` nor a runnable snippet that can reproduce the issue, so it's hard tell what and where goes wrong. Try to run the snippet from [the answer](http://stackoverflow.com/a/26299440/2072035) and tell us whether it leads to the same exception. – saaj Jan 30 '15 at 09:35
  • @saaj: Have updated with full error details. – zennith Feb 26 '15 at 10:40

2 Answers2

2

The issue may be related with some temporary file security which forbids reopening by a filename. Try replace shutil.copy2 call with:

with open('/path/that/you/have/permission/to', 'wb') as f:
  shutil.copyfileobj(theFile.file, f)
saaj
  • 23,253
  • 3
  • 104
  • 105
  • +1 Hey saaj!! "with open" worked like a charm. though i used the same path as i used previously. Can you please explain why? – zennith Feb 26 '15 at 11:45
  • @zennith Doesn't the first sentence of the answer convince you? For example read warning to [`tempfile.mktemp`](https://docs.python.org/2/library/tempfile.html?#tempfile.mktemp) or [`os.tempnam`](https://docs.python.org/2/library/os.html#os.tempnam). These are about prevention of a separate process from tempering your temp files. Python may use some Windows-specific function that creates temp file handles that you can't reopen. Accordingly, `shutil.copyfileobj` only reads already opened file-like object. – saaj Feb 26 '15 at 11:56
0

I guess windows has UAC restrict for launching the program, have you tried run the script under the administrator privilege?

Cui Heng
  • 1,265
  • 8
  • 10