Werkzeug: ファイルアップロード時のSpooledTemporaryFile例外

作成日 2018年08月18日  ·  13コメント  ·  ソース: pallets/werkzeug

今年の初めに、SpooledTemporaryFileが0.12.xから0.14.xにジャンプした後、ファイルのアップロードで例外をスローするという問題が発生しました。 深く調べる時間がなく、オンラインで多くを見つけることができず、それが私たちのせいであるか、いくつかの互換性のない依存関係に陥った場合、あなた方全員に汗を流したくありませんでした。 0.12.2に固定し、問題を検出できる小さなテストを作成して、次に進みます。

今夜、受信トレイにフラスコ管理者向けのSOの質問が表示されましたが、これは私たちが見たものと同じように聞こえたので、少なくとも取り上げる価値があると思いました。 SOの質問はあまり適切に表現されていないため、あまり役に立たない可能性があります(https://stackoverflow.com/questions/51858248/attributeerror-spooledtemporaryfile-object-has-no-attribute-translate)。

テストが役立つ場合:

def test_werkzeug_spooled_temp_file(self):
    """
    When we jumped from Werkzeug 0.12.x to 0.14.x, we started running into an error on any attempt to upload a CSV:

    File "/home/vagrant/site/videohub/admin.py", line 728, in import_content
    for line in csv.DictReader(io.TextIOWrapper(new_file), restval=None):
    File "/usr/local/lib/python3.6/dist-packages/werkzeug/datastructures.py", line 2745, in __getattr__
    return getattr(self.stream, name)
    AttributeError: 'SpooledTemporaryFile' object has no attribute 'readable'

    Until/unless we debug this, we need to stay on Werkzeug versions where it doesn't break.
    """

    with self.client:
        from videohub import admin

        admin.auth_admin = lambda: True

        try:
            what = self.client.post(
                "/admin/importcontent/",
                data={"csv": (io.BytesIO(b"my file contents"), "test.csv")},
                content_type="multipart/form-data",
            )
        except AttributeError as e:
            if (
                str(e)
                == "'SpooledTemporaryFile' object has no attribute 'readable'"
            ):
                self.fail("Werkzeug/SpooledTemporaryFile still exists.")

SOスレッドでは、一連のgithubの問題/ PR、Pythonの問題、およびすべて関連している可能性のある別のSOスレッドにインクを付けました。 それが消えた場合に備えて、ここで再リンクします。

最も参考になるコメント

再現が困難な場合はお詫び申し上げます。 私はまだ問題が発生していることを確認し、今日の午後、かなり簡潔な再現に向けて少し時間を費やしました。

その過程で、私はなんとか潜在的な回避策を見つけることができました。 私は回避策を広範囲にテストしていないので、それ自体が問題を引き起こすかどうかはわかりません(特に、 @ jdalegonzalezによる報告では、プラットフォームがここでの要因である可能性があります)。

依存関係:

pip install flask==1.0.2 pytest pytest-flask

テスト:

import pytest, io, csv
from flask import Flask, request


def fields(ob):
    return csv.DictReader(ob).fieldnames[0]


@pytest.fixture(scope="session")
def app():
    x = Flask(__name__)
    x.testing = True

    @x.route("/textio", methods=["POST"])
    def upload_file_textio():
        """succeeds with 0.12.2; fails with werkzeug==0.14.1;"""
        return fields(io.TextIOWrapper(request.files["csv"]))

    @x.route("/stringio", methods=["POST"])
    def upload_file_stringio():
        """potential workaround; succeeds for both versions"""
        return fields(io.StringIO(request.files["csv"].read().decode()))

    with x.app_context():
        yield x


@pytest.mark.parametrize("uri", ["/textio", "/stringio"])
def test_werkzeug_spooled_temp_file(client, uri):
    what = client.post(
        uri,
        data={"csv": (io.BytesIO(b"my file contents"), "test.csv")},
        content_type="multipart/form-data",
    )
    assert what.data == b"my file contents"

全てのコメント13件

価値があるのは、Werkzeugのバージョンほど単純ではないようです。 Alpine3.6のpython3.6.6で0.14.1を使用しており、すべてが機能しています。 Alpine3.8.1を使用してPython3.7.0でWerkzeug0.14.1を使用すると、問題が発生します。

https://github.com/python/cpython/pull/3249が最終的にPython側で修正をもたらす可能性があるようです。

HI @abathur-以下のようにリポジトリを作成しようとしましたが、エラーを再現できなかったようです=

app.py

import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename


UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def upload_file():

    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)

        file = request.files['file']

        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file', filename=filename))


    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''


from flask import send_from_directory

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)


if __name__ == '__main__':
    app.run()

大きなファイルを生成するためのスニペット

dd if=/dev/zero of=filename bs=1024 count=2M

Ubuntu - 18.10
Python -  3.6.7rc1

> pip freeze
Click==7.0
Flask==1.0.2
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.0
Werkzeug==0.14.1

/ cc @davidism

今のところ見る時間はあまりありませんが、今も再現するのに苦労しました。 私は現在、道路に出ており、午前中のフライトの準備をしていますが、今週後半に初期状態を再現できるかどうかを忘れないようにしています。

@jdalegonzalezこの問題の慣らし運転について、暫定的に写真を記入するのに役立つ可能性のあるメモがありますか?

再現が困難な場合はお詫び申し上げます。 私はまだ問題が発生していることを確認し、今日の午後、かなり簡潔な再現に向けて少し時間を費やしました。

その過程で、私はなんとか潜在的な回避策を見つけることができました。 私は回避策を広範囲にテストしていないので、それ自体が問題を引き起こすかどうかはわかりません(特に、 @ jdalegonzalezによる報告では、プラットフォームがここでの要因である可能性があります)。

依存関係:

pip install flask==1.0.2 pytest pytest-flask

テスト:

import pytest, io, csv
from flask import Flask, request


def fields(ob):
    return csv.DictReader(ob).fieldnames[0]


@pytest.fixture(scope="session")
def app():
    x = Flask(__name__)
    x.testing = True

    @x.route("/textio", methods=["POST"])
    def upload_file_textio():
        """succeeds with 0.12.2; fails with werkzeug==0.14.1;"""
        return fields(io.TextIOWrapper(request.files["csv"]))

    @x.route("/stringio", methods=["POST"])
    def upload_file_stringio():
        """potential workaround; succeeds for both versions"""
        return fields(io.StringIO(request.files["csv"].read().decode()))

    with x.app_context():
        yield x


@pytest.mark.parametrize("uri", ["/textio", "/stringio"])
def test_werkzeug_spooled_temp_file(client, uri):
    what = client.post(
        uri,
        data={"csv": (io.BytesIO(b"my file contents"), "test.csv")},
        content_type="multipart/form-data",
    )
    assert what.data == b"my file contents"

こんにちは@abathur

私はあなたのpytestリポジトリの実行をざっと見てみましたが、一見すると、以下の出力は問題を再現できるように見えます。 今後数日でさらに詳しく調べてみますが、フラスコ、pytest、器具に関しては初心者です😃

Testing started at 20:35 ...
/Users/jayCee/PycharmProjects/test_werkzeug_spooled_temp_file/venv/bin/python "/Users/jayCee/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-1/182.4505.26/PyCharm.app/Contents/helpers/pycharm/_jb_pytest_runner.py" --target test_werkzeug_spooled_temp.py::test_werkzeug_spooled_temp_file
Launching pytest with arguments test_werkzeug_spooled_temp.py::test_werkzeug_spooled_temp_file in /Users/jayCee/PycharmProjects/test_werkzeug_spooled_temp_file/test

============================= test session starts ==============================
platform darwin -- Python 3.6.6, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
rootdir: /Users/jayCee/PycharmProjects/test_werkzeug_spooled_temp_file/test, inifile:
plugins: flask-0.14.0collected 2 items

test_werkzeug_spooled_temp.py F
test_werkzeug_spooled_temp.py:27 (test_werkzeug_spooled_temp_file[/textio])
client = <FlaskClient <Flask 'test_werkzeug_spooled_temp'>>, uri = '/textio'

    @pytest.mark.parametrize("uri", ["/textio", "/stringio"])
    def test_werkzeug_spooled_temp_file(client, uri):

        what = client.post(
            uri,
            data={"csv": (io.BytesIO(b"my file contents"), "test.csv")},
>           content_type="multipart/form-data",
        )

test_werkzeug_spooled_temp.py:34: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
../venv/lib/python3.6/site-packages/werkzeug/test.py:840: in post
    return self.open(*args, **kw)
../venv/lib/python3.6/site-packages/flask/testing.py:200: in open
    follow_redirects=follow_redirects
../venv/lib/python3.6/site-packages/werkzeug/test.py:803: in open
    response = self.run_wsgi_app(environ, buffered=buffered)
../venv/lib/python3.6/site-packages/werkzeug/test.py:716: in run_wsgi_app
    rv = run_wsgi_app(self.application, environ, buffered=buffered)
../venv/lib/python3.6/site-packages/werkzeug/test.py:923: in run_wsgi_app
    app_rv = app(environ, start_response)
../venv/lib/python3.6/site-packages/flask/app.py:2309: in __call__
    return self.wsgi_app(environ, start_response)
../venv/lib/python3.6/site-packages/flask/app.py:2295: in wsgi_app
    response = self.handle_exception(e)
../venv/lib/python3.6/site-packages/flask/app.py:1741: in handle_exception
    reraise(exc_type, exc_value, tb)
../venv/lib/python3.6/site-packages/flask/_compat.py:35: in reraise
    raise value
../venv/lib/python3.6/site-packages/flask/app.py:2292: in wsgi_app
    response = self.full_dispatch_request()
../venv/lib/python3.6/site-packages/flask/app.py:1815: in full_dispatch_request
    rv = self.handle_user_exception(e)
../venv/lib/python3.6/site-packages/flask/app.py:1718: in handle_user_exception
    reraise(exc_type, exc_value, tb)
../venv/lib/python3.6/site-packages/flask/_compat.py:35: in reraise
    raise value
../venv/lib/python3.6/site-packages/flask/app.py:1813: in full_dispatch_request
    rv = self.dispatch_request()
../venv/lib/python3.6/site-packages/flask/app.py:1799: in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
test_werkzeug_spooled_temp.py:17: in upload_file_textio
    return fields(io.TextIOWrapper(request.files["csv"]))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <FileStorage: 'test.csv' ('text/csv')>, name = 'readable'

    def __getattr__(self, name):
>       return getattr(self.stream, name)
E       AttributeError: 'SpooledTemporaryFile' object has no attribute 'readable'

../venv/lib/python3.6/site-packages/werkzeug/datastructures.py:2745: AttributeError
.                                         [100%]
=================================== FAILURES ===================================
___________________ test_werkzeug_spooled_temp_file[/textio] ___________________
...
# truncated duplicate above output ...

環境

macOS Mojave 10.14
Python 3.6.6

pip freeze
atomicwrites==1.2.1
attrs==18.2.0
Click==7.0
Flask==1.0.2
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.0
more-itertools==4.3.0
pluggy==0.8.0
py==1.7.0
pytest==4.0.0
pytest-flask==0.14.0
six==1.11.0
Werkzeug==0.14.1

やあ、

以下のPRからのSpooledTemporaryFileの導入がこの問題の原因のようです...

PR:#1198:チャンク転送エンコーディングをサポート

  • 導入されたSpooledTemporaryFile-https://github.com/pallets/werkzeug/pull/1198/files#diff-91178c333961d75c285b7784d1b81cecR40)

PR:#1222-スプールされた一時ファイルがないプラットフォームのサポートが追加されました


SpooledTemporaryFileの実装をコメントアウトする-テストコードに合格したようですhttps://github.com/pallets/werkzeug/issues/1344#issuecomment -438836862

def default_stream_factory(total_content_length, filename, content_type,
                           content_length=None):
    """The stream factory that is used per default."""
    max_size = 1024 * 500
#    if SpooledTemporaryFile is not None:
#        return SpooledTemporaryFile(max_size=max_size, mode='wb+')
    if total_content_length is None or total_content_length > max_size:
        return TemporaryFile('wb+')
return BytesIO()

@abathurリンクからのように見えます- IOBaseの「想定される」抽象属性の実装が欠落しているため、 SpooledTemporaryFileクラスに問題があります。 また、これは512キロバイト(?)未満のファイルの場合に影響します。

以下のモンキーパッチをFormDataParser.default_stream_factoryに適用すると、テストコードhttps://github.com/pallets/werkzeug/issues/1344#issuecomment-438836862に合格するように見えます。

def default_stream_factory(total_content_length, filename, content_type,
                           content_length=None):
    """The stream factory that is used per default."""
    max_size = 1024 * 500
    if SpooledTemporaryFile is not None:
        monkeypatch_SpooledTemporaryFile = SpooledTemporaryFile(max_size=max_size, mode='wb+')
        monkeypatch_SpooledTemporaryFile.readable = monkeypatch_SpooledTemporaryFile._file.readable
        monkeypatch_SpooledTemporaryFile.writable = monkeypatch_SpooledTemporaryFile._file.writable
        monkeypatch_SpooledTemporaryFile.seekable = monkeypatch_SpooledTemporaryFile._file.seekable
        return monkeypatch_SpooledTemporaryFile
    if total_content_length is None or total_content_length > max_size:
        return TemporaryFile('wb+')
    return BytesIO()

または多分...

class SpooledTemporaryFile_Patched(SpooledTemporaryFile): 
    """Patch for `SpooledTemporaryFile exceptions on file upload #1344`
      - SpooledTemporaryFile does not fully satisfy the abstract for IOBase - https://bugs.python.org/issue26175 
      - bpo-26175: Fix SpooledTemporaryFile IOBase abstract - https://github.com/python/cpython/pull/3249

     TODO: Remove patch once `bpo-26175: Fix SpooledTemporaryFile IOBase abstract` is resolved..."""

    def readable(self):
        return self._file.readable

    def writable(self):
        return self._file.writable

    def seekable(self):
        return self._file.seekable

...

def default_stream_factory(total_content_length, filename, content_type, content_length=None):
    """The stream factory that is used per default.

    Patch: `SpooledTemporaryFile exceptions on file upload #1344`, Remove once `bpo-26175: Fix SpooledTemporaryFile IOBase abstract` is resolved...
      - SpooledTemporaryFile does not fully satisfy the abstract for IOBase - https://bugs.python.org/issue26175 
      - bpo-26175: Fix SpooledTemporaryFile IOBase abstract - https://github.com/python/cpython/pull/3249"""
    max_size = 1024 * 500
    if SpooledTemporaryFile is not None:
        # TODO: Remove patch once `bpo-26175: Fix SpooledTemporaryFile IOBase abstract` is resolved...
        SpooledTemporaryFile = SpooledTemporaryFile_Patched
        return SpooledTemporaryFile_Patched(max_size=max_size, mode='wb+')
    if total_content_length is None or total_content_length > max_size:
        return TemporaryFile('wb+')
    return BytesIO()

最善の行動方針は何でしょうか?

  • SpooledTemporaryFileのモンキーパッチを実装しますか? (これを行うにはおそらくもっと良い方法があります...)
  • 修正がPythonの新しいバージョンでリリースされるまで、 SpooledTemporaryFileの実装を避け、Pythonバージョンに応じてリダイレクトを追加しますか?
  • 私はまだこのドメインの初心者ですが、他のオプションがあると思いますか? :)

以前はSpooledTemporaryFileを使用していませんでしたが、元のコードが実行していたことを実行するための組み込みの方法のようでした。 それ以来、多くの問題を引き起こしています。 おそらく、 SpooledTemporaryFileを使用しないことに戻る必要があります。

😞bpo-26175では現在プルリクエストが進行中であることに注意してください。少なくとも、python / cpython#3249を参照してください。

@mjpietersとチャットすると、別のアイデアが生まれました。 streamにattrが存在しないが、 _file属性がある場合は、$ FileStorage.__getattr__ stream._file試すことができます。

class FileStorage:
    def __getattr__(self, name):
        try:
            return getattr(self.stream, name)
        except AttributeError:
            if hasattr(self.stream, "_file"):
                return getattr(self.stream._file, name)
            raise

こんにちは、今日はフラスコを1.0.2にアップグレードしてください。werkzeug> = 0.14

Python 3.6.7(ubuntu 18.04に付属)を使用した最後のバージョンのwerkzeug(0.14.1)でも同じエラーが発生しました:

AttributeError:'SpooledTemporaryFile'オブジェクトに属性がありません'読み取り可能'

修正をバージョン0.14に移植する予定はありますか?

ありがとう。

次のバージョンは0.15になります。 リリースの発表については、このリポジトリ、ブログ、またはhttps://twitter.com/PalletsTeamをフォローしてください。

このページは役に立ちましたか?
0 / 5 - 0 評価