Flask入门小项目 - 搭建极简博客(3)

新增登录、登出

一、

app.py中新增:

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form.get('username') != app.config.get('USERNAME'):
            error = 'Invalid username'
        elif request.form.get('password') != app.config.get('PASSWORD'):
            error = 'Invalid password'
        else:
            session['login'] = True
            flash('You\'re loginned successfully!')
            return redirect(url_for('show_entries'))
    return render_template('login.html', error=error)

@app.route('/logout')
def logout():
    session.pop('login', None)
    flash('You have logouted successfully')
    return redirect(url_for('show_entries'))

二、

login.html

{% extends "layout.html" %}

{% block body %}
  <h2>Login</h2>
  {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
  <form action="{{ url_for('login') }}" method=post>
    <dl>
      <dt>Username:
      <dd><input type=text name=username>
      <dt>Password:
      <dd><input type=password name=password>
      <dd><input type=submit value=Login>
    </dl>
  </form>
{% endblock %}

三、

layout.html

<!doctype html>
<html>
  <head>
    <title>Flaskr</title>
    <link rel='stylesheet' type='text/css' href="{{ url_for('static', filename='style.css') }}">
  </head>

  <body>
    <div class='page'>
      <h1>Flaskr</h1>

      <div class='metanav'>
        {% if not session.login %}
          <a href="{{ url_for('login') }}">log in</a>
        {% else %}
          <a href="{{ url_for('logout') }}">log out</a>
        {% endif %}
      </div>

      {% for message in get_flashed_messages() %}
        <div class='flash'>{{ message }}</div>
      {% endfor %}

      {% block body %}{% endblock %}
    </div>
  </body>
</html>

猜你喜欢

转载自www.cnblogs.com/holaworld/p/12672763.html
今日推荐