使用Flask,Flask登录,mod-wsgi切换到wsgi时,登录停止工作

时间:2018-01-30 02:49:43

标签: python apache flask mod-wsgi flask-login

我有一个烧瓶网络服务器为使用flask-login的用户进行基本帐户验证。如果我自己运行网络服务器帐户身份验证按预期工作。使用Apache和mod-wsgi运行烧瓶服务器后,当前用户会话在验证后很快就会被丢弃。因此,在任何刷新后,您都会被引导回登录页面。我相信我的虚拟主机文件设置不正确。

from app import app, lm
from flask import request, redirect, render_template, url_for, flash, json
from flask_login import login_user, logout_user, login_required, current_user
from .forms import LoginForm, SignUpForm
from .user import User
from werkzeug.security import generate_password_hash
from werkzeug.utils import secure_filename
from urllib.parse import unquote
import os

UPLOAD_FOLDER = os.path.dirname(os.path.realpath(__file__)) + "static" 
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def flash_errors(form):
    for field, errors in form.errors.items():
        for error in errors:
            flash( error,category='error' )
            print ((getattr(form, field).label.text,error))

@app.route('/')
def home():
    return render_template('home.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if request.method == 'POST' and form.validate_on_submit():
        user = app.config['USERS_COLLECTION'].find_one({"_id": form.username.data})
        if user and User.validate_login(user['password'], form.password.data):
            user_obj = User(user['_id'])
            login_user(user_obj)
            flash("Logged in successfully!", category='success')
            return redirect(request.args.get("next") or url_for("write"))
        flash("Wrong username or password!", category='error')
        print("Bad Login")
    return render_template('login.html', title='login', form=form)

@app.route('/signUp', methods=['GET', 'POST'])
def signUp():
    form = SignUpForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            user = app.config['USERS_COLLECTION'].find_one({"_id": form.username.data})
            if user:
                flash("username already taken", category='error')
            else:
                pass_hash = generate_password_hash(form.password.data)
                uId = app.config['USERS_COLLECTION'].insert({"_id": form.username.data, "password": pass_hash, "data":{"posts":[]}})
                user_obj = User(uId)
                login_user(user_obj)
                flash("Logged in successfully!", category='success')
                return redirect(request.args.get("next") or url_for("write"))
        else:
            flash_errors(form)

    return render_template('signUp.html', title='Sign Up!', form=form)


@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('login'))


@app.route('/write', methods=['GET', 'POST'])
@login_required
def write():
    if request.method == 'POST':
        # data = json.loads(unquote(request.query_string.decode().split('&')[0]))
        post = request.get_json()["post"]#data.get('post')
        print(post)

        current_user.write_post(post)
        return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 


    return render_template('write.html', posts=current_user.get_posts())

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

    current_user.deleteAllPosts()
    return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 

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

    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            print('No file part')
            return redirect(request.url, code=303)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            print('No selected file')
            return redirect(request.url, code=303)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 
@app.route('/photos2/<name>')
def photos2(name):
    return redirect( url_for('photos2', filename=name))

@app.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
    return render_template('settings.html')



@lm.user_loader
def load_user(username):
    u = app.config['USERS_COLLECTION'].find_one({"_id": username})
    if not u:
        return None
    return User(u['_id'])

我的另一个担心是以某种方式具有多个登录实例,用户正在通过一个进行身份验证,然后被另一个用户识别。任何帮助或建议将不胜感激。

我的代码中的其他一些相关内容。 WSGI文件:

async/await

查看:

function requestAddress() {
   return new Promise((resolve, reject) => {
      request(XXX,() =>{   
         // .....
         resolve(c)
      })
   })
}

async function isValid () {
    const res = await requestAddress(XXX)
    if () {} else {}
}

2 个答案:

答案 0 :(得分:1)

修复了,我的Flask会话就是问题,它没有持久化,因为秘密密钥是每次启动时随机生成的。我将密钥更改为静态变量,并且工作正常。

答案 1 :(得分:0)

类似的问题,不同的解决方案...

我在同一虚拟主机上有两个wsgi应用程序。

我忘记为每个应用程序定义不同的wsgiprocessgroup。