'str' object has no attribute ○○

Bottleのチュートリアル通りに書いたソースを実行してみたところ…

@route('/upload', method='POST')
def do_upload():
    category = request.forms.get('category')
    upload   = request.files.get('upload')
    name, ext = os.path.splitext(upload.filename)
    if ext not in ('.png', '.jpg', '.jpeg'):
        return 'File extension not allowed.'
    save_path = get_save_path_for_category(category)
    upload.save(save_path)
    return 'OK'

エラーが発生。

AttributeError: 'str' object has no attribute ‘filename’

と怒られてしまった。

name, ext = os.path.splitext(upload.filename)

が問題の部分。
PyCharmのデバッグモードでuploadの中身を見てみると、文字列でファイル名が入っていた。
それは怒られるわ、という話。

ファイルオブジェクトじゃなくテキストが入っていることがオカシイので、HTMLの方を確認してみたら、

<form action="/upload" method="post" enctype="">

enctypeが未指定だったことが原因。

<form action="/upload" method="post" enctype="multipart/form-data">

としてそこは解決。


今度は、

upload.save(save_path)

のsaveがAttribute:Errorに。

見ていたBottleのドキュメントが未リリースバージョン0.12についてのものだったという落とし穴が…orz
※使用中のBottleのバージョンは0.11.6
http://bottlepy.org/docs/dev/


http://stackoverflow.com/questions/15050064/how-to-upload-and-save-a-file-using-bottle-framework