如何在Flask中将相同的路由用于多种功能

时间:2018-10-15 06:42:38

标签: python-3.x flask

我当前正在使用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)

2 个答案:

答案 0 :(得分:0)

要调用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')

答案 1 :(得分:0)

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

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)