如何路由带有空参数的URL?
JFK-LAX售价100美元的作品:/username=Bob/flight_search/org=JFK&dst=LAX&price=100/
肯尼迪国际机场($ 100美元)会引发404错误:/username=Bob/flight_search/org=JFK&dst=&price=100/
没有任何值的dst=&
似乎引起了问题。
@app.route('/username=<username>/flight_search/org=<org>&dst=<dst>&price=<price>/')
def flights(username, org, dst, price):
flights = Flights.query.filter_by(org=org, dst=dst, price=price)
return render_template('search_results.html', data=flights)
答案 0 :(得分:2)
您应该考虑解析URL参数,而不是使用variable rules来传递数据。因此,请求网址应类似于:
example.com/flight_search/?username=foo&org=bar&dst=&price=123
如果未设置任何值,函数request.args.get()
将返回None
。在this answer的帮助下,您可以创建没有这些filter_data
值的字典None
,并在filter_by
函数中解压缩它们:
@app.route('/flight_search/')
def flights():
incoming_data['username'] = request.args.get('username')
incoming_data['org'] = request.args.get('org')
incoming_data['dst'] = request.args.get('dst')
# This also supports defaults:
incoming_data['price'] = request.args.get('price', default=100)
filter_data = {key: value for (key, value) in incoming_data.items()
if value}
flights = Flights.query.filter_by(**filter_data)
return render_template('search_results.html', data=flights)