开发者

Custom storage system in Django

I'm trying to write a simple custom storage system开发者_JS百科.

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜