在Python Flask中获取当前用户时遇到问题

时间:2018-06-02 14:14:17

标签: python-3.x flask-login

我对Python& Flask。我完全迷失在这里。我创建了一个示例Web应用程序。这里我在检索当前用户详细信息时遇到了问题。我已经尝试了2天,但没有运气。我的要求是我存储用户ID&一个文件中的密码,一旦登录该消息应出现在网上说“用户”:

# import the Flask class from the flask module
from flask import Flask,g,flash, render_template, redirect, get_flashed_messages, url_for, session,request
from flask_login import LoginManager,current_user,login_user,UserMixin,AnonymousUserMixin
from flask_sqlalchemy import SQLAlchemy
import sqlite3 as sql
import os
from os import urandom
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
app.config['SESSION_TYPE'] = 'filesystem'
file=open('C:/Users/RiazKhan/AppData/Local/Programs/Python/Python36-32/Scripts/musicdb/uid.txt')
db= SQLAlchemy(app)
#SECRET_KEY='\xbf\xe1sv\r\x89\xac\x06\x98~J\xe2&\x9a\xb1\xf76\x1b\xddTX\xeb\x0b\x8a'
uid=list()
upass=dict()
for line in file :
    x=line.strip()
    y=x.split(',')
    z=y[0]
    p=y[1]
    uid.append(z)
    upass[z]=p

login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader

class User(UserMixin):
    def is_active(self):
        """True, as all users are active."""
        return True

    def get_id(self):
        """Return the email address to satisfy Flask-Login's requirements."""
        return self.email

    def is_authenticated(self):
        """Return True if the user is authenticated."""
        return self.authenticated

    def is_anonymous(self):
        """False, as anonymous users aren't supported."""
        return False
def load_user(user_id):
    return User.get(user_id)
# use decorators to link the function to a url
@app.route('/')
def home():
    return "Hello, World!"  # return a string

@app.route('/welcome',methods=['GET', 'POST'])
def welcome():

        flash('User: '+ current_user.user_id +'Successfully Logged in')
        return render_template('welcome.html')  # render a template

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        fnd1=None
        fnd2=None
        for z,p in upass.items() :
            if request.form['username'] == z and request.form['password'] == p :
                fnd1="Found"
            else:
                fnd2="Not Found"
        if fnd1=="Found":
            return redirect(url_for('welcome'))
        elif fnd2 == "Not Found":
            error = 'Invalid Credentials. Please try again.'

    return render_template('login.html', error=error)
# start the server with the 'run()' method
@app.route('/list')
def list():
   con = sql.connect("C:/Users/RiazKhan/student_db.db")
   con.row_factory = sql.Row

   cur = con.cursor()
   cur.execute("select * from STUDENT")

   rows = cur.fetchall();
   return render_template("list.html",rows = rows)
@app.route('/logout', methods=['GET','POST'])
def logout():
    session.clear()
#    session.pop(request.form['username'], None)
    flash('Successfully Logged Out')
    #return render_template('login.html', msg)
    return redirect (url_for('login') )
if __name__ == '__main__':
    app.run(debug=True)

0 个答案:

没有答案