python - 如何使用 Flask 中的 Python 和 Flask-SQLAlchemy 将当前 session 设置为 'logged in'?

标签 python sqlite sqlalchemy flask flask-sqlalchemy

我正在尝试学习如何使用 Python 构建基本的 Flask 应用程序。我首先按照他们出色的教程制作了一个简单的博客。本教程要求您从 flask 导入 session。随后将其设置为“已登录”,只有在这种情况下用户才能撰写帖子。例如登录函数如下:

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

然后,另一个函数检查 session 是否确实处于“logged_in”状态:

@app.route('/add', methods=['GET', 'POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)
    g.db.execute('insert into entries (title, text) values (?, ?)',
                 [request.form['title'], request.form['text']])
    g.db.commit()
    flash('New entry was successfully posted')
    return redirect(url_for('show_entries'))

但是,当我尝试在应用程序中执行此操作时,我收到 500 Internal Server Error:

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

我认为这是因为在教程中使用了 sqlite 数据库,而当我收到错误时我正在使用 Flask-SQLAlchemy。这可能是问题的根源吗?如果是,是否有推荐的方法来做类似的事情?也就是说,允许应用程序检查是否有人登录?

下面是我的完整代码:

from flask import Flask, request, session, redirect, url_for, render_template
from flask.ext.sqlalchemy import SQLAlchemy



app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/z.db'
DEBUG = True
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)
    password = db.Column(db.String(160), unique=True)

    def __init__(self, username, email, password):
        self.username = username
        self.email = email
        self.password = password

    def __repr__(self):
        return '<User %r>' % self.username

@app.route('/', methods=['GET', 'POST'])
def home():
    #check to see if logged in
    if session['logged_in'] == True:
        note = "this text is displayed because you are logged in."              
    note=None
    if request.method == 'POST':
        new_user = User(request.form['username'], request.form['email'], request.form['password'])
        #before making the new user, check to make sure the entered information isn't already in the db
        if User.query.filter_by(username=request.form['username']).first() != None:
            note = "sorry, this username has already been taken"
        elif User.query.filter_by(email=request.form['email']).first() != None :
            note = "sorry, this email address is already associated with an account."   
        else:   
            db.session.add(new_user)
            db.session.commit()
            session['logged_in'] = True
            redirect(url_for('home'))
    return render_template('index.html', note=note)

@app.route('/login', methods=['GET', 'POST'])
def signin():
    note=None
    if request.method == 'POST':
        #get username and search for it in db
        tag = request.form['username']
        #if the entry contains '@', search db as email address
        if tag.find('@') != -1:
            user = User.query.filter_by(email=tag).first()
        else:
            user = User.query.filter_by(username=tag).first()   
        #if user exists, get password associated with it
        if user != None:
            password = user.password

            #see if db email equals email input in HTML
            if password == request.form['password']:
                session['logged_in'] = True
                return redirect(url_for('home'))
            else:
                note='wrong password'   
        else:
            #call an error message
            note='this username does not seem to exist. that is all i know'
    return render_template('login.html', note=note)         

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

提前非常感谢。

最佳答案

您需要设置app.secret_key才能使用 session :

In addition to the request object there is also a second object called session which allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing.

In order to use sessions you have to set a secret key. Here is how sessions work

关于python - 如何使用 Flask 中的 Python 和 Flask-SQLAlchemy 将当前 session 设置为 'logged in'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13326599/

相关文章:

javascript - ionicframework 使用 SQLite 进行 CRUD 操作

Android Realm 处理关系对象中的主键

python - SQLAlchemy 中的条件过滤

python - 刷新sqlalchemy中的分离实体

python - 操作后将 pandas 数据帧保存在循环中

python - 使用深色主题 Bootstrap css 样式破折号组件

python - 如何使用 'with' 语句对 Python 锁进行单元测试?

python - 根据 for 循环中的位置将直方图存储在一个大数组中

ruby-on-rails - Rails Heroku 数据库人口

python - 使用 SQLAlchemy 添加多对多关系