如何修复 Flask-Bootstrap4 Internal Server Error for double route on flask

How to fix Flask-Bootstrap4 Internal Server Error for double route on flask

我刚刚在本地主机上安装了 flask-bootstrap 和 运行。 但是在访问“/dinner/”路由时,我总是收到内部服务器错误消息。 如何修复此错误?谢谢

Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

Main.py

from flask import Flask, render_template 
from flask_bootstrap import Bootstrap

app = Flask(__name__)
bootstrap = Bootstrap(app)


@app.route('/dinner/')
@app.route('/dinner/<food>')
def index(food):
    return render_template('food.html', food=food, list=['sushi','pizza','hamburger'])

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

food.html

{% extends "bootstrap/base.html" %}

{% block title %} What is for dinner? {% endblock %}

{% block content %}

<div class="container">
    {% if food %}
        <div class="alert alert-success">
        <h1>I want that {{food}}</h1>
    {% else %}
        <div class="alert alert-info">
        <h1>Anything is fine!</h1>
    {% endif %}
        </div>

    {% if list %}
    <ul>
        {% for n in list %}
        <li><a href="/dinner/{{n}}">{{n}}</a></li>
        {% endfor %}
    </ul>
    {% endif %} 
</div>

{% endblock %}
@app.route('/dinner/') 
@app.route('/dinner/<food>') 

这表明如果你输入两个URL中的任何一个,就会调用索引函数。在 URL 之一中,您传递了一些参数,索引函数将接受该参数,但是当您传递第一个 URL 时,没有传递任何参数,这与索引函数冲突,因为它需要一些参数

更好的方法是这样做:

@app.route('/dinner/', defaults={'food':None})
@app.route('/dinner/<food>')

如果您不提供任何参数,这将处理默认情况。

我用这段代码修复了代码,它对我有用:

@app.route('/dinner/')
@app.route('/dinner/<food>')
def dinner(food=None):
    return render_template('food.html', food=food, list=['sushi','pizza','hamburger'])