python - Django 的 render_to_string 函数的 Flask 版本是什么?

标签 python flask

所以,我正在尝试通过翻译 this 来学习 Flask 的 TDD代码到 Flask。一段时间以来,我一直在尝试寻找如何将模板呈现为字符串。这是我尝试过的:

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'

templated.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在他的回答中提出了建议。

最佳答案

Celeo 是正确的,但还有两件事需要考虑(其中之一是 render_template 函数特有的):

首先,您修改后的函数似乎存在缩进问题。看起来您是在“with”语句之外调用 rv.data 。 “assertEqual”语句应与“assertIn”语句位于同一 block /缩进级别内。 (看起来您现在已将其放置在 block 之外。)

第二,更重要的是,flask 中的 render_template 函数在输出的 HTML 的开头和结尾添加换行符。 (您可以通过将以下命令打印到 stdout 从 python 交互式 shell 验证这一点:

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())

这应该可以解决问题。

关于python - Django 的 render_to_string 函数的 Flask 版本是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30065635/

相关文章:

python - 相当于 Django ORM 中的 group_concat

python - 为什么 localhost :5000 not work in Flask?

javascript - 使用 Flask 实现强制页面刷新的最佳方法是什么?

python - HTML 多空格对齐

python - psycopg2 关闭连接池

python - 使用上述值简化数据框列部分的有效方法

python - 持续时间的 Bokeh x_axis_type?

python - 无论 Content-Type header 如何,都在 Python Flask 中获取原始 POST 正文

python - Pusher:Swift (iOS) 发布者/服务器到 Raspberry Python 订阅者/客户端

Python 三角函数返回意外值