tags:

views:

37

answers:

1

I'm trying to write a simple custom storage system.

I need only that my storage system duplicate files from a few FTP servers.

Subclass of storage looks like:

from django.core.files.storage import Storage
from settings import MEDIA_ROOT, MEDIA_URL
import ftplib
import os



class FTPStorage(Storage):
    """FTP Storage class for Django pluggable storage system."""

    def __init__(self, mediaroot=MEDIA_ROOT, base_url=MEDIA_URL):
        self._netrc=open('netrc')
        self._machine=[]
        self._login=[]
        self._password=[]


 def _save(self, name, content):
     content.open()
        if hasattr(content, 'chunks'):
            content_str = ''.join(chunk for chunk in content.chunks())
        else:
            content_str = content.read() 
        for line in netrc: #read netrc file
            old=line.strip()
            line=line.strip().split()
            if old.startswith("machine"): machine.append(line[-1])
            if old.startswith("login"): login.append(line[-1])
            if old.startswith("password"): password.append(line[-1])
        for i in range(len(machine)):
            try:
               ftp = ftplib.FTP(machine[i])
               ftp.login(login[i],password[i])
            except Exception,e:
                print e
            else:
                ftp.cwd("PublicFolder")
                ftp.storbinary("STOR " + os.path.basename(name), StringIO(content_str), "rb", 8*1024)  
        return name

But now it give me the error:

line:20, in __init__
if hasattr(content, 'chunks'):
Name error: Global name is not defined.

Can I just write the _save method, so it'll work?

A: 

Your problem has more to do with the format of your code, and not the logic of it. That is, you have some syntax errors.

The error message you included states that the if hasattr(content, 'chunks'): line occurs in the __init__ method, which suggests that the interpreter believes you to be defining the _save method as a function within the init method's scope. Your indentation, while not entirely clear here on StackOverflow, seems messy and may be the cause of this confusion. Python is very sensitive to indentation errors.

Joseph Spiros
The first point is correct, but the second is not. The expression is perfectly valid - look up [generator expressions](http://www.python.org/dev/peps/pep-0289/).
Daniel Roseman
Interesting, I was somehow unaware of generator expressions. I've edited my answer accordingly.
Joseph Spiros