deMangler
deMangler

Reputation: 477

Django file object always 0 bytes when uploaded from python requests

I have been trying to upload a file to django REST using python requests.

I put the file, and some other data, to the server.

r = self.session.put(
    f"{hello_url}/shadow_pbem/savefile_api/",
    files=test_files,
    data={"hash": test_file_hash, 'leader': 78}, 
    headers=good_token_header,
)

I get a 200 response, the model saves all the data correctly as expected, including a correctly named save file in /media, except the save file in /media is always 0 bytes.

This is how I create the file object...

with open(testfile_path, "rb") as testfile:

...and verify the length, which is not 0.

testfile.seek(0, os.SEEK_END)
filesize = testfile.tell()

I create the files object for upload...

test_files = {
    "file": ("testfile.zip", testfile, "application/zip")
}

I put some code in the view to verify, and the file object in the view is there, but it is 0 bytes.

here is the relevent part of the view. It seems to work fine, but all files are 0 bytes.

class SaveFileUploadView(APIView):
    parser_class = (FileUploadParser,)

    def put(self, request):
        if "file" not in request.data:
            raise ParseError("Empty content")

        f = request.data["file"]
        print(f"file {f} size:{f.size}")
        # prints file testfile.zip size:0

        # rest of view works fine...

I have tried with various files and formats, also using post. Files are always 0 bytes.

Any help appreciated I am going crazy....

Upvotes: 2

Views: 1042

Answers (1)

AKX
AKX

Reputation: 168957

If you do

testfile.seek(0, os.SEEK_END)
filesize = testfile.tell()

as you say, you'll need to also rewind back to the start – otherwise there is indeed zero bytes for Requests to read anymore.

testfile.seek(0)

Upvotes: 2

Related Questions