6

Is it possible to use the requests module to interact with a FTP site? requests is very convenient for getting HTTP pages, but I seem to get a Schema error when I attempt to use FTP sites.

Is there something that I am missing in requests that allows me to do FTP requests, or is it not supported?

rypel
  • 4,686
  • 2
  • 25
  • 36
zephyrthenoble
  • 1,377
  • 3
  • 13
  • 20
  • 1
    Are you looking for HTTP interaction or just straight FTP protocols? If so you're probably better off using ftplib. Assuming that's an option. Requests doesn't have native support for FTP so you'd have to use urllib2 if you want something similar to requests. – Bob Jun 03 '14 at 19:20
  • 1
    I was using requests to do HTTP interaction, and was hoping that I could use it as well for FTP because requests was so easy to use. If that's not an option, then I will try ftplib for my FTP transfer. – zephyrthenoble Jun 09 '14 at 16:43
  • 1
    You'd want to use ftplib if you're looking at transferring files back and forth between remote machines and your local machines. It's quite simple and almost identical to requests in its syntax usage. If you need sftp then look into paramiko. Otherwise you'll be fine with ftplib. – Bob Jun 09 '14 at 17:06

1 Answers1

3

For anyone who comes to this answer, as I did, can use this answer of another question in SO.

It uses the urllib.request method.

The snippet for a simple request is the following (in Python 3):

import shutil
import urllib.request as request
from contextlib import closing
from urllib.error import URLError

url = "ftp://ftp.myurl.com"
try:
    with closing(request.urlopen(url)) as r:
        with open('file', 'wb') as f:
            shutil.copyfileobj(r, f)
except URLError as e:
    if e.reason.find('No such file or directory') >= 0:
        raise Exception('FileNotFound')
    else:
        raise Exception(f'Something else happened. "{e.reason}"')
Gustavo Lopes
  • 3,794
  • 4
  • 17
  • 57