Python Flask:将Jinja变量传递给后端 [英] Python Flask: pass Jinja variable to backend

查看:88
本文介绍了Python Flask:将Jinja变量传递给后端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Flask Web应用程序,其中显示了我从TSV文件(使用Pandas)读取的表格.对于每一行,我将显示索引,一些文本,一个标签(正/负),一个日期和一个更改标签"按钮.

我希望能够在TSV文件中为单击更改标签"按钮的特定文本更改标签.我当时在考虑使用/edit/< index> 这样的URL,以便可以使用URL中传递的索引在TSV中找到相应的行并进行更改,但是没有运气.

例如,当我单击表第一行中的更改标签"按钮时,URL为/edit/0

这就是我所拥有的.

Python Flask应用

  @ app.route('/admin',methods = ['GET','POST'])def admin():如果request.method =='GET':返回render_template('admin.html')如果request.method =='POST':如果request.form ['submit'] =='Manage':from_date = '01 -01-1900'to_date = '01 -01-2900'df = pd.read_csv('dataset.tsv',sep ='\ t',encoding ='utf-8')索引= df.index.values.tolist()文字= df ['文字'] .values.tolist()标签= df ['标签'] .values.tolist()date = df ['date'].values.tolist()数据=邮政编码(索引,文本,标签,日期)返回render_template('admin.html',from_date = from_date,to_date = to_date,data = data)@ app.route('/edit/< id>',methods = ['GET','POST'])def edit():如果request.method =='GET':返回render_template('admin.html')如果request.method =='POST':#TODO,打开TSV文件并更改标签返回render_template('admin.html') 

admin.html

 <!doctype html>< head>< link rel ="stylesheet" media ="screen" href ="static/bootstrap.min.css">< link rel ="stylesheet" href ="static/bootstrap-theme.min.css">< meta name ="viewport" content ="width = device-width,initial-scale = 1.0"></head>< div class ="container">< table class ="table">< thead>< tr>< th scope ="col">#</th>< th scope ="col">文本</th>< th scope ="col">标签</th>< th scope ="col">日期</th>< th scope ="col">编辑</th></tr></thead>< tbody>{索引,文字,标签,日期%,数据%}< tr>< th> {{index}}</th>< th> {{text}}</th>< th> {{标签}}</th>< th> {{date}}</th>< th>< form action ="/edit/{{index}}" method ="post" role ="form"><输入type ="submit" name ="submit" value =更改标签" class ="btn btn-info"></form></th></tr>{%endfor%}</tbody></table></div></html> 

我知道问题与中的< form action ="/edit/{{index}}""method =" post"role =" form> 有关> admin.html ,因为它无法在URL中传递索引.当我单击任何按钮时,它会将我重定向到/edit/,而没有任何索引.可以通过某种方式在URL中传递变量 {{index}} 还是应该以不同的方式进行?

解决方案

为什么不使用隐藏的表单输入?在您的表单中,添加隐藏的输入元素:

  {%用于索引,文本,标签,数据中的日期%}< tr>< th> {{index}}</th>< th> {{text}}</th>< th> {{标签}}</th>< th> {{date}}</th>< th>< form action ="/edit" method ="post" role ="form">< input type ="hidden" id ="index" name ="index" value ="{{index}}"><输入type ="submit" name ="submit" value =更改标签" class ="btn btn-info"></form></th></tr>{%endfor%} 

然后在您的路线上

  @ app.route('/edit',methods = ['GET','POST'])def edit():如果request.method =='GET':返回render_template('admin.html')如果request.method =='POST':索引= int(request.form ['index'])#现在使用`index`更改您的TSV返回render_template('admin.html') 

I have a simple Flask web app showing a table that I read from a TSV file (using Pandas). For each row, I'm showing the index, some text, a label (positive/negative) a date, and a "change label" button.

I want to be able to change the label in the TSV file for the specific text for which I clicked the "change label" button. I was thinking of using a URL like /edit/<index> so I can use the index passed in the URL to find the corresponding row in the TSV and change it, but without luck.

For instance, when I click the button "change label" in the first row of the table, the url would be /edit/0

Here's what I have.

Python Flask app

@app.route('/admin', methods=['GET', 'POST'])
def admin():
    if request.method == 'GET':  
        return render_template('admin.html')

    if request.method == 'POST':
        if request.form['submit'] == 'Manage':
            from_date = '01-01-1900'
            to_date = '01-01-2900'

            df = pd.read_csv('dataset.tsv', sep='\t', encoding='utf-8')
            indexes = df.index.values.tolist()
            texts = df['text'].values.tolist()
            labels = df['label'].values.tolist()
            dates = df['date'].values.tolist()
            data = zip(indexes, texts, labels, dates)

        return render_template('admin.html', from_date=from_date, to_date=to_date, data=data)

@app.route('/edit/<id>', methods=['GET', 'POST'])
def edit():
    if request.method == 'GET':
        return render_template('admin.html')

    if request.method == 'POST':
        # TODO, open TSV file and change label
        return render_template('admin.html')

admin.html

<!doctype html>
<head>
    <link rel="stylesheet" media="screen" href ="static/bootstrap.min.css">
    <link rel="stylesheet" href="static/bootstrap-theme.min.css">
    <meta name="viewport" content = "width=device-width, initial-scale=1.0">
</head>

<div class="container">
    <table class="table">
        <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">Text</th>
                <th scope="col">Label</th>
                <th scope="col">Date</th>
                <th scope="col">Edit</th>
            </tr>
        </thead>
        <tbody>
            {% for index, text, label, date in data %}
            <tr>
                <th>{{ index }}</th>
                <th>{{ text }}</th>
                <th>{{ label }}</th>
                <th>{{ date }}</th>
                <th>
                    <form action="/edit/{{ index }}" method="post" role="form">
                        <input type="submit" name="submit" value="Change Label" class="btn btn-info">
                    </form>
                </th>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>
</html>

I know the problem has to do with the <form action="/edit/{{ index }}" method="post" role="form"> in the admin.html, because it fails to pass the index in the URL. When I click any button it just redirects me to /edit/ without any index. Is it possible somehow to pass the variable {{ index }} in the URL or should this be done differently?

解决方案

Why don't you utilize hidden form inputs? In your form, add the hidden input element:

{% for index, text, label, date in data %}
<tr>
    <th>{{ index }}</th>
    <th>{{ text }}</th>
    <th>{{ label }}</th>
    <th>{{ date }}</th>
    <th>
        <form action="/edit" method="post" role="form">
            <input type="hidden" id="index" name="index" value="{{ index }}">
            <input type="submit" name="submit" value="Change Label" class="btn btn-info">
        </form>
    </th>
</tr>
{% endfor %}

Then in your route:

@app.route('/edit', methods=['GET', 'POST'])
def edit():
    if request.method == 'GET':
        return render_template('admin.html')

    if request.method == 'POST':
        index = int(request.form['index'])
        # Now use `index` to change your TSV
        return render_template('admin.html')

这篇关于Python Flask:将Jinja变量传递给后端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆