【发布时间】:2019-12-07 06:54:59
【问题描述】:
我有一个带有用户登录系统的烧瓶应用程序。我现在注意到一些与用于注册和登录网站的电子邮件地址区分大小写有关的问题。 TL;DR 问题:如何获取 Flask Form 的小写字母并使用它来评估用户是否存在于我的数据库中?
例子
假设用户 John Smith 在网站上注册了一个帐户。他在 John.Smith@gmail.com 注册,但随后使用 John.smith@gmail.com 登录。截至目前,该网站将他们视为两个不同的用户。我希望这被认为是同一个用户。
在 Python(我的强项)中,我只需将 str(form.email.data).lower() 用作注册表单,然后将其写入数据库中的用户表。然后,当有人尝试登录时,我也会这样做。换句话说,我总是会考虑小写的注册和登录。
但我正在努力在 Jinja 中实现这一点,尽管它与 Python 相似。
register.html 的电子邮件部分:
<div class="form-group">
{{ form.email.label(class="form-control-label") }}
{% if form.email.errors %}
{{ form.email(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.email.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.email(class="form-control form-control-lg") }}
{% endif %}
</div>
routes.py中的注册码:
@app.route("/register", methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = RegistrationForm()
admins = ['admin@admin.com',
'admin@admin.com']
if form.validate_on_submit():
new_user_email = form.email.data.lower() ###<-----NOTE THAT THIS IS LOWER CASE
admin_test = True if new_user_email in admins else False
invited_test = Invites.query.filter(Invites.invited_email == new_user_email).count()
print(admin_test, invited_test)
if (invited_test == 0) & (admin_test == False): # Not invited and not and admin --> REJECT
flash(
'Sorry but it looks like you were not invited. Please contact a current member for an invitation.',
'warning')
elif (invited_test > 0) | (admin_test == True): ## if they have been invited OR if they are admin
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
#create User object
user = User(username=form.username.data.lower(), ###<----NOTE LOWER CASE
email=form.email.data.lower(), ###<----NOTE LOWER CASE
password=hashed_password)
#write to db
db.session.add(user)
db.session.commit()
#alert user
flash('Welcome to. Enjoy the platform.', 'success')
return redirect(url_for('login'))
else:
#Not invited condition
flash('Sorry but it looks like you were not invited to __. Please contact a current member for an invitation.', 'warning')
return render_template('register.html', title='Register', form=form)
login.html 的电子邮件部分:
<div class="form-group">
{{ form.email.label(class="form-control-label") }}
{% if form.email.errors %}
{{ form.email(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.email.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.email(class="form-control form-control-lg") }}
{% endif %}
</div>
【问题讨论】:
标签: flask flask-sqlalchemy flask-wtforms