使用Flask格式化结果pag

2024-10-04 07:37:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python和烧瓶的初学者。我用python编写了一个简单的应用程序(容器填充器),它接收一个数字作为输入(茶匙),并返回一个元组列表。你知道吗

到目前为止,我已经能够使用flask来正确格式化初始表单,以便使用一些html和css“很好地”显示。当输入一个数字并提交时,它只是简单地显示一个元组列表。烧瓶代码如下所示:

from flask import Flask, request, render_template

from container_filler import ContainerFiller

app = Flask(__name__)

@app.route('/', methods=['GET'])
def form():
    return render_template('index.html')

@app.route('/submit', methods=['POST'])
def submit():    
    return str(ContainerFiller().calculate(int(request.form['teaspoons'])))

我现在想做的是基于str返回,我想改变背景颜色,也许添加图标。你知道吗

例如,如果返回值是[('gallon',42)],我想用一整页蓝色来表示gallon。我一直在看教程和其他人的代码,他们通常如何使用烧瓶,我不能翻译成我的代码。到目前为止,我尝试过这样的方法,但没有效果:

烧瓶代码:

@app.route('/submit', methods=['POST']
def submit():
    a = str(ContainerFiller().calculate(int(request.form['teaspoons'])))
    for c,d in a:
       if c == 'gallon':
          return render_template('some.html')
       else:
          return a

但这只是给了我一个'内部服务器错误',所以它让我觉得这不是一个合法的方式。但我一点也不知道该怎么办。你知道吗

*编辑

Traceback (most recent call last):
return self.view_functions[rule.endpoint](**req.view_arg
  File "/home/James/Documents/Container/service.py", line 17, in submit
for c, d in a:
ValueError: not enough values to unpack (expected 2, got 1)

Tags: 代码formappreturn烧瓶requestdefhtml
1条回答
网友
1楼 · 发布于 2024-10-04 07:37:39

如果你的方法ContainerFiller().calculate返回一个元组,你必须用元组作为参数来呈现一个模板。你知道吗

像这样

@app.route('/submit', methods=['POST']
def submit():
    a = str(ContainerFiller().calculate(int(request.form['teaspoons'])))
    return render_template('some.html', value=a )

并将模板引擎中的值与jinja一起使用,并根据a的值更改样式!你知道吗

所以基本上在你的一些.html,您应该有:

<div>
This is a text inside a div element.
We are still in the div element.
</div>

根据c的值改变syle:

<style>
div {

{% for c, d in value %}
        {% if c == 'gallon' %}
        background-color: lightblue;
        {% elif c == 'avalue' %}
        background-color: red ;
        {% else %}
        background-color: green;
        {% endif %}
    {% endfor %}

}

相关问题 更多 >