【问题标题】:Can't retrieve variable from url with Flask app after submitting search form提交搜索表单后,无法使用 Flask 应用程序从 url 检索变量
【发布时间】:2015-12-05 15:23:38
【问题描述】:

我想在用户提交搜索表单后呈现一个新视图。我以与其他视图相同的方式制作它,但不幸的是这次没有发生任何事情,我无法从应用程序路由中检索内容。 (所以这个问题不是this问题的重复,这个问题只有在提交表单后才会出现,它在其他所有情况下都能正常工作。)我在表单中写了一些东西,提交它,然后浏览器中的url发生变化,但无论如何视图都不会改变。我几乎可以肯定这是因为搜索中的?=,但不知道我应该如何在Python 代码中处理它们。

实际上,当我提交表单时,我的浏览器会将我重定向到这样的网址:

http://domain/.com/?search=content+from+textfield

这就是我尝试从搜索字段中捕获内容并在 Flask 端呈现新视图的方式:

@app.route('/?search=<url_content>', methods=['POST'])
def hello_url(url_content): 
return render_template("search-results.html", searchString = url_content])

如果有人能告诉我正确的方法,我将不胜感激,基本上我只想在点击搜索按钮后在hello_url 函数中检索&lt;url_content&gt; 的值。

这是我的html:

<form>
 <div class="form-group">
    <input type="search" class="form-control text-center input-lg" id="inputSearch" name="search" placeholder="search">
    </div>
     <br>
<div class="text-center"><button type="submit" class="btn btn-primary btn-lg">Search!</button></div>
</form>

【问题讨论】:

  • @RobertMoskal 这个问题是关于基本情况的,当你提出意见时,正如我提到的,我的问题只有在提交表单后才会出现。
  • 我还要指出,您的视图函数响应POST,但由于您的表单缺少一个动作,它被隐式设置为GET。无论哪种方式,您在 POST 方法而不是表单数据中查找查询字符串数据都有点奇怪。

标签: python forms flask


【解决方案1】:

您将使用&lt;variable&gt; 捕获的url 参数与在request.args 中访问的查询参数混淆了。从您的路由定义中删除查询参数并在视图中访问它。

from flask import request

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/search')
def search():
    search = request.args.get('search')  # will be None if form wasn't submitted
    # do something with search
    return render_template('search.html', search=search)

index.html:

<form action="{{ url_for('search') }}">
    <input name="search"/>
    <input type="submit" value="Search"/>
</form>

【讨论】:

    【解决方案2】:

    你有几个错误。首先,您在服务器端错误地指定了路由。您无法在烧瓶路由上捕获或指定查询参数。你可以有类似的东西

    @app.route('/search')
    

    其次,您需要在表单上提供操作和方法。所以

    <form action="{{ url_for("search") }}" method="POST">
    

    如果您不指定方法,它将作为 GET 发送,并且字段将显示为查询参数。如果您发布帖子,则可以在服务器端检索字段:

    request.form['inputSearch']
    

    我介绍了 /search 路由,但您可以从根“/”执行相同的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多