如何在渲染模板时对Flask中的可选参数进行记录

2024-06-08 23:02:00 发布

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

我正在创建一个基本的搜索函数来查询两个不同表中的列。如果有一列与给定的搜索词匹配,它应该用结果呈现该模板,并将参数传递到结果html中。如果它匹配这两列,它应该将参数传递到结果html中。我想通过一个或另一个或两者。起始位置只是一个表单,用于发布到以下代码:

@app.route('/search', methods=['GET', 'POST'])
def search():
    if request.method == 'POST':
        print "inside of request POST"
        search_term = request.form['search_term']
        poems = session.query(Poem).filter(Poem.name.contains(search_term)).all()
        authors = session.query(Author).filter(Author.name.contains(search_term)).all()

        if any(search_term in p.name for p in poems):
            print "found a poem!"
            if any(search_term in a.name for a in authors):
                print "found an author!"
                return render_template('results.html', poems=poems, authors=authors)
            else:
                print "only poems"
                return render_template('results.html', poems=poems)
        elif any(search_term in a.name for a in authors):
            print "only authors!"
            return render_template('results.html', authors=authors)
    else:
        print "in the last else"
        return render_template('search.html')

在这里是什么结果.html公司名称:

<div id="container">

    {% for p in poems %}
    <div class="poem-title">{{p.name}}</div><br />
    {% endfor %}

    {% for a in authors %}
    <div class="author-title">{{a.name}}</div><br />
    {% endfor %}

</div>

我得到的一个错误是:

回溯(最近一次呼叫):

  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
TypeError: results() takes no arguments (1 given)

Tags: inpyappflasksearchrequestlibpackages