问题
I am using Python Flask to build a website. I can login, but not log out. The logout button does not respond when I click it.
The logout function:
@bp.route('/logout')
def logout():
session.pop('userName')
return redirect(url_for('index.html'))
The code for the logout button:
<button type="button">Logout</button>
The logout button is in the file ...\sent\templates\base.html The logout function is in the file ...\sent\blueprints\auth.py
Do I need an onclick handler to call the Python function? Do I need to import the function since it is in another directory? Or could it be something else that I am missing?
回答1:
If you assign an onclick handler to the button, you'd need to write the Javascrpt to send an AJAX request, and do something with the response. However that route is performing a redirect, instead of returning JSON, so probably better just direct the user to the /logout
URL. For this, use an anchor tag instead of a button:
<a href="{{ url_for('logout') }}">Logout</a>
If you want to make this appear as an actual button, then you could still style it as so.
For example, with the bootstrap CSS library you could simply assign the relevant classes to that anchor:
<a href="{{ url_for('logout') }}" class="btn btn-primary">Logout</a>
来源:https://stackoverflow.com/questions/63541731/using-flask-how-does-the-logout-button-call-the-logout-function