Python “我怎么能?”;重定向";到另一个URL并使用Flask传递列表对象
关于URL更改,我有一个非常基本的问题。 假设我有一个HTML页面Python “我怎么能?”;重定向";到另一个URL并使用Flask传递列表对象,python,flask,Python,Flask,关于URL更改,我有一个非常基本的问题。 假设我有一个HTML页面http://example.com/create包含一些输入字段的表单。从这个输入字段中,我想创建一个python列表,该列表应用于生成另一个HTML页面http://example.com/show_list包含基于python列表值的列表 因此,http://example.com/create是: @app.route('/create', methods=['GET', 'POST']) def create():
http://example.com/create
包含一些输入字段的表单。从这个输入字段中,我想创建一个python列表,该列表应用于生成另一个HTML页面http://example.com/show_list
包含基于python列表值的列表
因此,http://example.com/create
是:
@app.route('/create', methods=['GET', 'POST'])
def create():
if request.method == 'POST':
some_list = parse_form_data_and_return_list(...)
return render_template( "show_list.html", some_list=some_list) #here's the problem!
return render_template( "create.html")
假设parse\u form\u data\u和
接受用户输入并返回一个包含一些string
值的列表。
我在困扰我的那句话中加了一句评论。我马上就回来,但首先给你页面的模板(http://example.com/show_list
),应在用户输入后加载:
{% block content %}
<ul class="list">
{% for item in some_list %}
<li>
{{ item }}
</li>
{% endfor %}
</ul>
{% endblock content %}
但是在这种情况下,我不知道如何将list
对象传递给show\u list()
。当然,我可以将列表中的每一项解析为URL(因此将其发布到http://example.com/show_list
),但这不是我想做的
正如您可能已经认识到的那样,我对web开发非常陌生。我想我只是使用了一个错误的模式,或者还没有找到一个简单的API函数来实现这个功能。因此,我恳请您向我展示一种解决我的问题的方法(简短总结):呈现
show_列表
模板,并将URL从http://example.com/create
至http://example.com/show_list
使用在create()
方法/路线中创建的列表。如果列表不是很长,您可以在查询字符串上传递它,例如逗号分隔:
comma_separated = ','.join(some_list)
return redirect(url_for('show_list', some_list=comma_separated))
# returns something like 'http://localhost/show_list?some_list=a,b,c,d'
然后在视图中的模板中,您可以像这样迭代它们:
{% for item in request.args.get('some_list', '').split(',') %}
{{ item }}
{% endfor %}
对于较长的列表,或者如果不想在查询字符串中公开,也可以将列表存储在:
然后在模板中:
{% for item in session.pop('my_list', []) %}
{{ item }}
{% endfor %}
除了在会话中存储列表外,您还可以简单地将表单操作更改为post到新路由。然后处理“显示列表”路径中的表单数据并呈现模板 表格标题:
<form action="{{ url_for('show_list') }}" method="post">
我并不一定反对使用会话存储,但我认为不使用它更干净,因为您不必担心清除会话变量。为什么要将
/create
重定向到刷新页面后无法使用的URL?这不是很安静或用户友好。你能更详细地解释一下你目前的情况吗?啊!会议记录,就这样。我怎么能监督这件事?我想今天有太多的新信息了。谢谢你,伙计!
{% for item in session.pop('my_list', []) %}
{{ item }}
{% endfor %}
<form action="{{ url_for('show_list') }}" method="post">
@app.route('/show_list', methods=['GET', 'POST'])
def show_list():
if request.method == 'POST':
some_list = parse_form_data_and_return_list(...)
return render_template("show_list.html")
else:
# another way to show your list or disable GET
return render_template("show_list.html")