flask如何记录登录状态

davie5201314
  • 3
新手上路,请多包涵

我用flask做了一个简单的站点,希望导航栏所有链接都不能直接访问,而是需要经过登录验证才能访问,为此,我每一个route节点都添加了@login_required,但是发现一个问题,每次访问导航栏都需要进入了登录页面,登录一次,我希望一次登录,所有页面都能访问,该怎么做?

import logging
import os
import psutil
import socket
#import MySQLdb
from datetime import datetime, timedelta
import uuid
import locale
from download import logdir
from flask import Flask, render_template, request, session, jsonify, Response, Blueprint, current_app, g, send_from_directory, flash, redirect, url_for
from flask_login import login_required, current_user, LoginManager, login_user
from werkzeug.local import LocalProxy
from psdash.helpers import socket_families, socket_types

logger = logging.getLogger('psdash.web')
webapp = Blueprint('psdash', __name__, static_folder='static')

webapp.SECRET_KEY='\xf8\xa1\x01v\xeb8\xe7n\xdchI{y\xef:~\x1d\x1d\xf9\x05_\x04\xbb\x07'
webapp.USERNAME='admin'
webapp.PASSWORD='admin'

@webapp.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != webapp.USERNAME:
            error = 'Invalid username'
        elif request.form['password'] != webapp.PASSWORD:
            error = 'Invalid password'
        else:
            session.permanent = True
            session['username'] = request.form['username']
            flash('You were logged in')
            return redirect(url_for('psdash.index'))
    return render_template('login.html', error=error)
@webapp.route('/logs')
@login_required
def view_logs():
    available_logs = current_service.get_logs()
    available_logs.sort(cmp=lambda x1, x2: locale.strcoll(x1['path'], x2['path']))

    return render_template(
        'logs.html',
        page='logs',
        logs=available_logs,
        is_xhr=request.is_xhr
回复
阅读 5.7k
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏