pythonmkstemp

Python mkstemp suffix


I have the following piece of code that handles the image upload for me in a Django Project that I work on:

def upload_handler(source):
    fd, filepath = tempfile.mkstemp(prefix=source.name, dir=MEDIA_ROOT)
    with open(filepath, 'wb') as dest:
        shutil.copyfileobj(source, dest)
        return MEDIA_URL + basename(dest.name)

All is working fine with the upload part but mkstemp is saving my image with an additional 6 random suffix after the extension (Ex. test.png -> test.pngbFVeyh). Even if I pass the suffix in the second code line it appends it but also with the additional 6 random characters. Other odd thing that is happening is that in the upload folder (MEDIA_ROOT in my case) it is created alongside another empty plain text document type file with the same name as the picture (Ex. test.pngbFVeyh). I've read the documentation regarding mkstemp but I didn't find any alternative solution.


Solution

  • The name is random-generated because it's the purpose of tempfile.mkstemp. The file with that name is created because it's how tempfile.mkstemp works. It is also opened and the file descriptor is returned to you in fd which you ignore. You don't seem to understand how tempfile.mkstemp should be used and you probably need to use something else instead.