aioftp

0.27.2 · active · verified Thu Apr 16

aioftp is an asynchronous FTP client and server library for Python's asyncio framework, providing a simple yet extensible API for file transfer operations. It is currently at version 0.27.2 and is actively maintained, with updates released irregularly as needed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `aioftp.Client` with its `context` manager to connect to an FTP server, list files recursively, and download specific files (e.g., MP3s). It gracefully handles connection and FTP status errors. Remember to replace placeholder credentials and host with actual FTP server details for real-world usage, ideally through environment variables.

import asyncio
import aioftp
import os

async def download_mp3_files(host, port, user, password):
    """Connects to an FTP server, lists files, and downloads MP3s."""
    print(f"Connecting to ftp://{user}@{host}:{port}...")
    try:
        async with aioftp.Client.context(host, port, user, password) as client:
            print("Connected and logged in.")
            async for path, info in client.list(recursive=True):
                if info.get("type") == "file" and path.suffix == ".mp3":
                    print(f"Downloading {path.name}...")
                    await client.download(path, path.name)
                    print(f"Downloaded {path.name}.")
    except aioftp.StatusCodeError as e:
        print(f"FTP error: {e}")
    except ConnectionRefusedError:
        print(f"Connection refused by the FTP server at {host}:{port}.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

async def main():
    FTP_HOST = os.environ.get('FTP_HOST', 'ftp.example.com') # Replace with a real FTP server for testing
    FTP_PORT = int(os.environ.get('FTP_PORT', '21'))
    FTP_USER = os.environ.get('FTP_USER', 'anonymous')
    FTP_PASS = os.environ.get('FTP_PASS', 'anonymous@example.com')

    # Example with a mock server if you don't have a real one
    # For a real server, ensure FTP_HOST, FTP_PORT, FTP_USER, FTP_PASS are set correctly
    # For testing, you might need a local FTP server or a public test server (be cautious)
    print("Starting aioftp client example...")
    await download_mp3_files(FTP_HOST, FTP_PORT, FTP_USER, FTP_PASS)

if __name__ == "__main__":
    # To run this, you need an accessible FTP server. For anonymous access:
    # export FTP_HOST='test.rebex.net' # or another public test server
    # export FTP_USER='demo'
    # export FTP_PASS='password'
    # Then run 'python your_script.py'
    asyncio.run(main())

view raw JSON →