February 13, 2015
How To Write a Custom Management Command in Django for Automating File Retrieving Process from FTP Server
by Yaseen DarDjango provides us with the flexibility to write our own custom management commands. Custom management commands are simply classes in Django inherited from django.core.management.base.BaseCommand. These commands lie inside management/commands folder of your Django Project.
For example: YourDjangoProject/management/commands/
Requirements for Retrieving Files from an FTP server :
- FTP server address
- Account information(username and password on FTP server if FTP is password protected)
- Directory containing the files
Here is the Code!
#getfromfpt.py import ftplib import os from django.core.management.base import BaseCommand class Command(BaseCommand): args = 'TAKES NO ARGUMENT' #this command takes no argument def handle(self, *args, **options): print 'this command gets the files from an FTP Server' username = 'yaseen' #this is your username on ftp server, yaseen in my case password = '*******' #this is the password directory ='/mydirectory/' #this is the directory on FTP server which contains files ftp = ftplib.FTP('ftp.trialx.smartteam.com') #establish the connection ftp.login(username, password) #login with the username and password provided ftp.cwd(directory) #changing to the directory containing the files for filename in ftp.nlst(): # ftp.nlist() Returns a list of file names in the directory fhandle = open(filename, 'wb') ftp.retrbinary('RETR ' + filename, fhandle.write) #retrieve the file fhandle.close()
To use this command we have to type the file name after manage.py inside the Django Project
i.e python managy.py getfromftp
Automating the File Retrieving Process
To automate this process we can setup a Cronjob which runs the command at the desired time.
- Type crontab –e in the terminal
- Click Enter
- Add your cron
for example
30 10 * * * Pythonpath Projectpath/manage.py getfromftp
Pythonpath is the path of the python in the environment( if virtual environment is used) and Projectpath is the path of Django Project.
The above example sets up a Cronjob which runs everyday at 10:30am to get files from the Ftp server.
Excellent post. I was checking continuously this blog
and I am impressed! Very helpful info particularly the last part 🙂 I
care for such information a lot. I was seeking this certain info for a long time.
Thank you and good luck.