Some general ideas for the client:
- It needs to establish a session. This is both so that it can see the file copy progress of the files it is copying and no other (possibly malicious) third party can see it. This can be done with some sort of a token. This can be stored as a cookie and the server can read this to see what session the request is from.
- You need the client to keep requesting the state at a steady interval. This is called polling.
So, all your client has to do is request to establish a session, request which folder needs to be copied (Possibly needing to request a directory tree), and then make a request for which folder needs to be copied where, and keep making requests for the progress every few seconds or minutes until it is done. In the mean time, if the user wishes to cancel it, send a cancel request to some endpoint.
On the server side, there are many technologies to do this. django
is the most popular, but this seems like a smaller project, so might I recommended flask
.
As for the actual task, shutil.copytree()
is what you are looking for. It takes a custom copy function, which you can specify to update a sessions "currently copying" file when a new file needs to be copied:
import shutil
def copy_dir(session_id, source, destination):
def copy_fn(src, dest):
if sessions[session_id]['data'].aborted:
return # Stop copying once requested.
# Or however your session data is structured
sessions[session_id]['data'].current_copy = [src, dest]
shutil.copy2(src, dest) # Actual copy work
shutil.copytree(source, destination, copy_function=copy_fn)
To get the percentage of how much of the file has been copied, compare the size of the file that is being copied to to the file it is being copied from.
Another way to get the percentage of copying, os.walk
on a directory to generate all the file names, then open the files and copy it in chunks. Update the progress every few chunks. Note that this is very error prone.