【问题标题】:How can I use the same route for multiple functions in Flask如何在 Flask 中为多个功能使用相同的路由
【发布时间】:2026-01-30 19:25:01
【问题描述】:

我目前正在使用python3Flask;我有两个使用相同路由定义的函数。 - 如何让index2 打印。

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/')
def index():
    if request.authorization and request.authorization.username == 'user1' and request.authorization.password == 'pass1':
        return '<h1>You are logged in</h1>'
    return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})

@app.route('/')
def index2():
    print('In Index 2')

if __name__ == '__main__':
    app.run(debug=True)

【问题讨论】:

  • 两个函数共享同一个 app.route。给 index2 函数一个不同的应用路由,并从 index 函数中调用它
  • 如何从 index() 中调用 index2()?

标签: python-3.x flask


【解决方案1】:

您有多种选择;其中之一是从index 函数中调用index2 函数:

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/')
def index():
    if request.authorization.username == 'user1' and request.authorization.password == 'pass1':
        index2() # you can return index2() if that's the logged in page.
        return '<h1>You are logged in</h1>'

    return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})


def index2():
    print('In Index2')

if __name__ == '__main__':
    app.run(debug=True)

第二个选项是根据调用的 http 方法区分这两个函数:

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/')
def index():
    if request.authorization.username == 'user1' and request.authorization.password == 'pass1':
        return '<h1>You are logged in</h1>'

    return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})

@app.route('/', methods=['POST'])
def save():
    print('Save operations here')

if __name__ == '__main__':
    app.run(debug=True)

第三种选择是使用不同的参数:

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/')
def index():
    if request.authorization.username == 'user1' and request.authorization.password == 'pass1':
        return '<h1>You are logged in</h1>'

    return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})

@app.route('/<string:page_name>')
def index2(page_name):
    print(f"{page_name}")

if __name__ == '__main__':
    app.run(debug=True)

【讨论】:

    【解决方案2】:

    要调用 index2,请尝试以下快速而肮脏的代码。我相信您可以改进以使其适合您的需求。

    @app.route('/')
    def index():
        if request.authorization and request.authorization.username == 'user1' and request.authorization.password == 'pass1':
            return '<h1>You are logged in</h1> <a href="{{ url_for('index2') }}">Click me to go to index2</a>'
    
        return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
    
    @app.route('/index2')
    def index2():
        print ('In Index2')
    

    【讨论】:

    • 为什么要新建一个app.route?据我所知,您不需要这样做。
    最近更新 更多