1

我正在尝试学习如何使用 Python 构建基本的 Flask 应用程序。我首先按照他们的优秀教程制作了一个简单的博客。本教程让您sessionflask. 稍后将其设置为“登录”,并且只有在这种情况下,用户才能写帖子。例如登录功能如下:

@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)

然后,另一个函数检查会话是否确实在“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:

内部服务器错误

服务器遇到内部错误,无法完成您的请求。服务器过载或应用程序出错。

我认为这是因为在教程中使用了 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()        

提前谢谢了。

4

1 回答 1

3

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

除了请求对象之外,还有一个名为 session 的对象,它允许您存储从一个请求到下一个请求的特定于用户的信息。这是在 cookie 之上为您实现的,并以加密方式对 cookie 进行签名。这意味着用户可以查看您的 cookie 的内容但不能修改它,除非他们知道用于签名的密钥。

为了使用会话,您必须设置一个密钥。这是会话的工作方式

于 2012-11-10T23:06:46.887 回答