How To Write a Custom Management Command in Django for Automating File Retrieving Process from FTP Server

by Yaseen Dar
Django provides us with the flexibility to write our own custom management commands. Custom management commands are simply classes in Django inherited from 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!
import ftplib
import os
from 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('')  #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


To use this command we have to type  the file name after inside the Django Project

i.e   python 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/ 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.

One thought on “How To Write a Custom Management Command in Django for Automating File Retrieving Process from FTP Server”

  1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Tools & Practices

Tools and Technologies we use at Applied

Contact us now

Popular Posts