Search code examples
pythonftptwistedftp-server

Twisted - Simple file completed event for FTP server


I want to use twisted for some basic FTP server, just like this example:

from twisted.protocols.ftp  import FTPFactory, FTPRealm
from twisted.cred.portal    import Portal
from twisted.cred.checkers  import AllowAnonymousAccess, FilePasswordDB
from twisted.internet       import reactor

#pass.dat looks like this:
# jeff:bozo
# grimmtooth:bozo2

p = Portal(FTPRealm('./'), (AllowAnonymousAccess(), FilePasswordDB("pass.dat")))
f = FTPFactory(p)
reactor.listenTCP(21, f)
reactor.run()

...with one simple customization: I want to fire an event when a file upload (STOR) is completed successfully, so that my custom code can adequately handle this file.

I found no documentation for FTPFactory or FTP that helps me doing this. Should I overload the FTP object or some other object? How to wire everything up?

I have done simple custom HTTP servers with twisted in the past and it was pleasantly easy, but I can find nearly no material about FTP.


Solution

  • First off, this is just a modification of Rakis' answer. Without his answer this would not exist. His one just wouldn't work on my setup. It also may just be that the API has changed, since this is 5 years later.

    class MyFTP (ftp.FTP):
    
        def ftp_STOR(self, path):
    
            d = super(MyFTP, self).ftp_STOR(path)
    
            def onStorComplete(d):
                print 'STORED', repr(d), path
                return d
    
            d.addCallback(onStorComplete)
    
            return d
    
    f = ftp.FTPFactory( some_portal_object )
    f.protocol = MyFTP