我目前正在使用python3和Flask; 我使用相同的路由定义了两个函数。-如何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)
Run Code Online (Sandbox Code Playgroud)
Jul*_*eri 12
您有多种选择;其中之一是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)
Run Code Online (Sandbox Code Playgroud)
第二个选项是根据被调用的 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)
Run Code Online (Sandbox Code Playgroud)
第三个选项是使用不同的参数:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3649 次 |
| 最近记录: |