Flask入门小项目 - 搭建极简博客(3)添加登录、登出功能

目录:

完整程序点这

零、效果

在数据库users表中添加几个用户就能登录了

一、app.py

# app.py

from flask import Flask, render_template, flash, request, session, redirect, url_for, abort
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, login_required, login_user, logout_user

app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)

# flask-login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"

from models import *


@app.route('/')
def index():
    articles = Article.query.all()
    articles_dict = [dict(id=article.id, title=article.title, text=article.text) for article in articles]
    return render_template('index.html', articles=articles_dict)


@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        info = get_user_info(username, password)
        if type(info) != str:  # 验证
            user = User(id)
            login_user(user)
            session['login'] = True
            flash('You\'ve logged in successfully!')
            return redirect(url_for('index'))
        else:
            error = info

    return render_template('login.html', error=error)


@app.route('/logout')
@login_required
def logout():
    logout_user()
    session.pop('login', None)
    flash('You have logged out successfully')
    return redirect(url_for('index'))


@app.route('/signup')
def signup():
    return 'Hello World!'


@app.route('/post')
def post():
    return 'Hello World!'


@app.route('/delete')
def delete():
    return 'Hello World!'


@login_manager.user_loader
def load_user(id):
    print(id)
    return User(id)


def get_user_info(username, password=None):
    user = User.query.filter(User.username == username).all()
    if len(user) == 0:
        return 'username does not exist!'

    if user[0].password == password:
        return user[0].id
    return 'wrong password'


if __name__ == '__main__':
    app.run(debug=True)

最上面加了3句话配置login_manager,增加了load_user和get_user_info函数,修改了login和logout函数

二、login.html

login.html

{% extends "base.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 %}

posted on 2020-04-10 12:55  HolaWorld  阅读(329)  评论(0编辑  收藏  举报

导航