Issue
How can I route a URL with empty params?
JFK-LAX for $100 works: /username=Bob/flight_search/org=JFK&dst=LAX&price=100/
JFK-(anywhere) for $100 throws 404 error: /username=Bob/flight_search/org=JFK&dst=&price=100/
The dst=&
without any value seems to cause the problem.
@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)
Solution
Rather than using variable rules to pass this data through, you should consider parsing URL params. So the request URL would look more like:
example.com/flight_search/?username=foo&org=bar&dst=&price=123
The function request.args.get()
will return None
if no value is set. With help from this answer you could then create the dictionary filter_data
without these None
values, and unpack them in the filter_by
function:
@app.route('/flight_search/')
def flights():
incoming_data = {}
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)
Answered By - v25
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.