2012-04-21 15 views
1

現在、ftpサーバーからファイルをloalディレクトリに保存しています。しかし、私はImageFieldを使って物事をより管理しやすくしたいと考えています。ここDjangoのftpダウンロードからImageFieldに保存する方法

は、現在のコードスニペットは、ここで

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 "画像"をどのような順序で扱うべきか混乱しています

+0

「_download_cb」とは何ですか?どのように 'file_handle'とやりとりしますか? – ilvar

答えて

1

あなたは_download_cbが不足していますので、私は使用していません。
参考文献The File Object of 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)) 
関連する問題