Using Flask, how does the Logout Button call the logout function?

我们两清 提交于 2021-01-29 08:48:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!