1

現在、ftp サーバーからローカル ディレクトリにファイルを保存しています。しかし、より管理しやすくするために ImageFields の使用に移行したいと考えています。

ここに現在のコードスニペットがあります

file_handle = open(savePathDir +'/' +  fname, "wb")            
nvcftp.retrbinary("RETR " + fname, _download_cb)
file_handle.close()    
return savePathDir +'/' +  fname

初めてのマッチングはこちら。今のところ、互換性のためだけにパスを返しています。後で、モデルを介して保存されたファイルに適切にアクセスします。

new_image = CameraImage(video_channel = videochannel,timestamp = file_timestamp)
file_handle = new_image.image.open()
nvcftp.retrbinary("RETR " + fname, _download_cb)
file_handle.close()
new_image.save()
return new_image.path()

これは正しいです?file_handle と ImageField の「画像」を処理する順序について混乱しています。

4

1 に答える 1

1

あなたがいなくなっ_download_cbたので、私はそれを使用していません。
Refs Django のファイル オブジェクト。試す

# retrieve file from ftp to memory,
# consider using cStringIO or tempfile modules for your actual usage

from StringIO import StringIO
from django.core.files.base import ContentFile
s = StringIO()
nvcftp.retrbinary("RETR " + fname, s.write)
s.seek(0)  
# feed the fetched file to Django image field
new_image.image.save(fname, ContentFile(s.read()))
s.close()

# Or
from django.core.files.base import File
s = StringIO()
nvcftp.retrbinary("RETR " + fname, s.write)
s.size = s.tell()
new_image.image.save(fname, File(s))
于 2012-04-21T10:48:40.863 に答える