2

そこで、このコードを Flaskに翻訳することで、Flask の TDD を学ぼうとしています。しばらくの間、テンプレートを文字列にレンダリングする方法を見つけようとしています。これが私が試したことです:

render_template(...)
render_template_string(...)
make_response(render_template(...)).data

そして、それらのどれも機能していないようです。

それぞれの場合のエラーは

"...templating.py", line 126, in render_template
    ctx.app.update_template_context(context)
AttributeError: 'NoneType' object has no attribute 'app'

の関数ですtemplating.pyrender_template

私のテストコードは次のとおりです。

def test_home_page_can_save_POST_request(self):
    with lists.app.test_client() as c:
        c.get('/')
        rv = c.post('/', data = {'item_text':"A new list item"})

        # This test works
        self.assertIn("A new list item", rv.data)

    # This test doesn't
    self.assertEqual(rv.data,flask.make_response(flask.render_template('home.html',new_item_text='A new list item')).data)

次のhome.htmlように:

<html>
<body>
    <h1>Your To-Do list</h1>
    <form method="POST">
        <input name="item_text" id="id_new_item" placeholder="Enter a to-do item" />
    </form>

    <table id="id_list_table">
        <tr><td>{{ new_item_text }}</td></tr>
    </table>
</body>
</html>

編集:エラーは使用されている実際の機能とは無関係である可能性があるため、さらにファイルを追加しました。私はCeleoが彼の答えで提案したものを正確に使用しています。

4

2 に答える 2

1

あなたは正しい道を進んでいますmake_response

response = make_response(render_template_string('<h2>{{ message }}</h2>', message='hello world'))

それで、

response.data

<h2>hello world</h2>

そのresponseオブジェクトはここに文書化されています。

于 2015-05-06T02:50:02.333 に答える
1

Celeo は正しいですが、考慮すべき点が 2 つあります (そのうちの 1 つは render_template 関数に特有のものです)。

まず、修正した関数にインデントの問題があるようです。「with」ステートメントの外で rv.data を呼び出しているようです。「assertEqual」ステートメントは、「assertIn」ステートメントと同じブロック/インデント レベル内にある必要があります。(現時点ではブロックの外に配置しているようです。)

次に、さらに重要なことに、flask の render_template 関数は、出力された HTML の最初と最後に改行文字を追加します。(次のコマンドを stdout に出力することにより、python 対話型シェルからこれを確認できます。

flask.render_template('home.html',new_item_text='A new list item').data  # adds '\n' at start & end

得られる出力には、出力の最初と最後に改行文字 ("\n") が含まれます。

したがって、以下に示すように、strip() 関数を使用して出力を削除してみてください。

def test_home_page_can_save_POST_request(self):
    with lists.app.test_client() as c:
        c.get('/')
        rv = c.post('/', data = {'item_text':"A new list item"})

        self.assertIn("A new list item", rv.data)

        # Suggested Revision
        self.assertEqual(rv.data,flask.make_response(flask.render_template('home.html',new_item_text='A new list item')).data.strip())

うまくいけば、うまくいくはずです。

于 2015-05-13T05:28:41.813 に答える