gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:45 27 4
gpt4 key购买 nike

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

<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName testing.myApp.io
# ProxyPreserveHost On
# ProxyPass / http://127.0.0.1:8888/
# ProxyPassReverse / http://127.0.0.1:8888/
LogLevel info

WSGIDaemonProcess myApp user=myUser threads=1 home=/var/www/myApp/

WSGIScriptAlias / /var/www/myApp/myApp.wsgi
WSGIPassAuthorization On

<Directory /var/www/myApp/app/>
WSGIProcessGroup myApp

WSGIApplicationGroup %{GLOBAL}

Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/myApp/app/static
<Directory /var/www/myApp/app/static/>
Order allow,deny
Allow from all
</Directory>


Include /etc/letsencrypt/options-ssl-apache.conf
#ServerAlias testing.myApp.io
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/testing.myApp.io/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/testing.myApp.io/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>

我的另一个担忧是,不知何故有多个 Flask 登录实例,用户正在被一个实例验证,然后不被另一个实例识别。任何帮助或建议将不胜感激。

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

#!/usr/bin/python3
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/myApp/")

from app import app as application

浏览次数:

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'])

最佳答案

已修复,事实证明我的 Flask session 是问题所在,它没有持续存在,因为每次启动时都会随机生成 key 。我将 key 更改为静态变量,效果非常好。

关于python - 使用 Flask、Flask 登录、mod-wsgi 切换到 wsgi 时登录停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48513139/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com