You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask POST请求下重定向失败问题求助

Hey there! Let's figure out why your search isn't redirecting to a new page. Looking at your code snippet, I notice you're handling the POST request in the home route, but there's no logic to actually send the user to a results page after processing their search query. Let's walk through the fixes step by step:

1. Add Redirect Logic to Your POST Handler

Right now, your code runs the SQL query but doesn't send any response telling the browser to navigate elsewhere. You need to either redirect to a dedicated search results route (best practice to avoid duplicate form submissions) or render a results template directly.

Example: Redirect to a dedicated results route

First, define a new route for displaying search results:

@app.route('/search-results')
def search_results():
    # Grab the search query from the URL parameters
    search_query = request.args.get('search')
    
    # Run your SQL query here (use parameterized queries to avoid SQL injection!)
    sql_search = '''
        SELECT Food.name, Food.area, Food.price, Food.description, 
               Food.available_amount, Food.score, AVG_PRICE, AVG_SCORE, 
               User.selling_score 
        FROM Food 
        LEFT JOIN(SELECT ...) AS agg ON ...
        WHERE Food.name LIKE %s OR Food.area LIKE %s
    '''
    # Execute with parameters to stay safe
    cursor.execute(sql_search, (f'%{search_query}%', f'%{search_query}%'))
    results = cursor.fetchall()
    
    # Render the results template with fetched data
    return render_template('search_results.html', results=results, query=search_query)

Then update your home route to redirect to this new route after capturing the search input:

@app.route('/', methods=['GET','POST'])
def home():
    if request.method == "POST":
        search = request.form['search']
        print(search)
        # Redirect to the results route, passing the search query as a parameter
        return redirect(url_for('search_results', search=search))
    # For GET requests, just render the home page
    return render_template('home.html')
2. Double-Check Your Frontend Form

Make sure your HTML form is set up correctly to send the POST request to the right place:

<form method="POST" action="/">
    <input type="text" name="search" placeholder="Search for dishes or regions...">
    <button type="submit">Search</button>
</form>

If the action attribute points to the wrong URL or the method isn't set to POST, the form data won't reach your home route's POST handler.

3. Guard Against SQL Errors

If your SQL query has a syntax error or fails to execute, it might throw an exception that stops the redirect from happening. Wrap your query logic in a try-except block to catch issues:

try:
    cursor.execute(sql_search, (f'%{search_query}%', f'%{search_query}%'))
    results = cursor.fetchall()
except Exception as e:
    print(f"Query error: {e}")
    # Redirect back to home with an error message if needed
    return redirect(url_for('home', error="Oops, search failed. Try again!"))

Also, never concatenate user input directly into SQL queries—this opens you up to SQL injection attacks. Always use parameterized queries like the example above.

4. Ensure No Code Blocks the Redirect

Make sure there's no code after the return redirect(...) line that could overwrite the response. Since return exits the function immediately, any code after it won't run, but it's good to double-check you don't have accidental logic that might interfere.

Once you add this redirect logic, users should be sent to the /search-results page where you can display their search results.

内容的提问来源于stack exchange,提问作者Heng Zong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:53:35