简体   繁体   中英

Django list of files return an empty array

I'm starting with Django, so I'm pretty new to this. I'm sending a file to the Django server, saving it, trying to get the last file (the one I just send) from the saved folder and then I want to perform some processes on that file, after that I want to delete the original file. I already managed to upload and save the file to the filesystem, but I'm having trouble selecting this file from the folder.

I'm trying select and remove it this way:

@api_view(['POST', 'GET'])
def geojson_to_shape_view(request):
    if request.method == 'POST':
        serializer = FileSerializer(data=request.data)
        if serializer.is_valid():
            # serializer.save() calls .create() in serializers.py
            file = serializer.save()

            # Get last saved file
            print("Analyzing last posted file...")
            list_of_files = glob.glob('../media/temp_files/*')
            print(list_of_files)
            if list_of_files:
                latest_file = max(list_of_files, key=os.path.getctime)
                print("Deleting last posted file...")
                try:
                    os.remove(latest_file)
                    pass
                except:
                    print("Can't remove the file")

            return Response(FileSerializer(file).data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

And this code returns:

Analyzing last posted file...
[]

I tried to run a script in the same folder with these file interactions and it run with no problems, so I thinking is some django permission issue. I also tried to change the path to settings.MEDIA_ROOT + 'temp_files/*' , but the problem persists.

As already mentionned by AKX, your issue is here:

list_of_files = glob.glob('../media/temp_files/*') 

Relative path are resolved against the current working directory, which can actually be just anything, so you need to use absolute path if you expect your code to work reliably.

But it isn't possible to work with relative paths?

Well, technically yes, but as I stated above - and as you already found out by yourself -, the final result is totally unpredictable. And no, changing the current working directory is not a solution - it's unreliable too (some other code - possibly in another thread - can change it back under your feet), and since it requires knowing the absolute path to switch to, it's much simpler to just build a proper absolute path.

NB: you may want to have a look at os.path and (python3.x) the path module for filesystem path manipulations.

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