简体   繁体   中英

Hashing file within DRF (POST HTTP request)

I'm creating a REST API and I'm not particularly savvy in Django. I'd like to post an uploaded file, but before doing so I'd like to create the sha256 of the file, like so:

def sha256sum(filename):
    h = hashlib.sha256()
    b = bytearray(128*1024)
    mv = memoryview(b)
    with open(filename, 'rb', buffering=0) as f:
        for n in iter(lambda : f.readinto(mv), 0):
            h.update(mv[:n])

    return h.hexdigest()

In order for this to work, I require the actual file (or file path), and not the actual filename. My code in my viewsets.py:

def create(self, request):
    serializer = FileSerializer(data=request.data) 
    f = request.FILES["file"] # just gives the filename
    print(request.META)
    if serializer.is_valid():
        f = serializer.save() 
        print(f"f: {f}")
        res_name = sha256sum(f)
        print(f"res_name: {res_name}")

        return Response(serializer.data, status=status.HTTP_201_CREATED)

Any ideas where I am going wrong?

I had request.FILES['file'] is a InMemoryUploadedFile. After digging a bit dip it appeared that this file was already "open", so I just removed the open from my function, like so:

def sha256sum(filename):
    h = hashlib.sha256()
    b = bytearray(128*1024)
    mv = memoryview(b)
    for n in iter(lambda : filename.readinto(mv), 0):
        h.update(mv[:n])

    return h.hexdigest()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM