Flask-Security:自定义注册

时间:2017-02-13 01:06:46

标签: python flask flask-sqlalchemy registration flask-security

我尝试使用Flask-Security登录和注册用户。但是,我试图做两件事。第一个是将默认/注册更改为/注册我相信我已经正确完成了。 第二是我想自定义注册表。我可以加载页面,但每当我提交表单时都没有任何反应。没有数据发送到后端或插入sqlite数据库。

我也不确定是否需要编写自己的app.route函数来处理创建新用户和/或检查它们是否已存在。我希望能够使用flask-security的注册,但只是调整它。如果可能的话。

这是我的主要python文件:

from flask import Flask, redirect, flash, session, request, render_template
from flask_sqlalchemy import SQLAlchemy

import os, time


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['DATABASE'] = 'data.db'
app.config['SECURITY_TRACKABLE'] = True
app.config['SECURITY_REGISTERABLE'] = True
app.config['SECURITY_REGISTER_URL'] = '/signup'
app.config['SECURITY_REGISTER_USER_TEMPLATE'] = 'security/register.html'
# enable this if you want to send email and confirm
# app.config['SECURITY_CONFIRMABLE'] = True
db = SQLAlchemy(app)

from user import Security, User, user_datastore
from forms import logform, signupform, RegisterForm

security = Security(app, user_datastore, register_form=signupform,  login_form=logform,
                    confirm_register_form=signupform)

db.create_all()
db.session.commit()


@app.route('/')
def hello_world():
    log = logform(csrf_enabled=False)
    flash("HELLO.")
    return render_template("index.html", form=log)


@app.route('/login')
def login():
    print "/LOGIN REQUESTED"
    form = logform(csrf_enabled=False)
    return render_template("security/login_user.html", login_user_form=form, security=security)


#not sure if I need this function at all
@app.route('/signup', methods=['GET', 'POST'])
def signup():
    print "/SIGNUP REQUESTED"
    form = signupform(csrf_enabled=False)
    # form = RegisterForm()

    if request.method == 'GET':
        return render_template("security/register.html", register_user_form=form, security=security)

    else:
        #log = logform(csrf_enabled=False)
        if form.validate_on_submit() or form.validate():
            print "HERE NOW SOMEONE SUBMITTED SOMETHING"
            print form.email.data
            print form.username.data
            print form.password.data
            user_datastore.create_user(form)
            db.session.commit()

        return redirect('/')

我不确定是否需要/ signup功能,或者flask-security是否会在默认情况下处理它。 接下来是我的logform和signupform类:

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo
from flask_security.forms import LoginForm, RegisterForm, Form


class logform(LoginForm):
    login = StringField('login', validators=[DataRequired()])
    # password = PasswordField('password', validators=[DataRequired()])


class signupform(RegisterForm):
    # email = StringField('email', validators=[Email(), DataRequired()])
    username = StringField('username', [DataRequired()])
    # password = PasswordField('password', validators=[DataRequired()])

这是我尝试使用的当前注册表单。我不确定是否应该使用url_for('注册'),因为flask-security的默认注册表单使用url_for_security(' register')。

<!DOCTYPE html>

{% extends "base.html" %}

{% block content %}

    <div id="signup">
        <h1>Create Account.</h1>
        <h3>TESTING</h3>
        {# not sure what to put as my action. default flask-security uses url_for_security('register') #}
        <form id="logfrm" name='register_form' method="POST" action="{{ url_for('signup') }}">
            {# figure out how to make input required #}

            {{ register_user_form.email(placeholder="email", type="email") }}<br>
            {{ register_user_form.username(placeholder="username") }}<br>
            {{ register_user_form.password(placeholder="password", type="password") }}<br>
            {# register_user_form.confirm(placeholder="confirm password") #}<br>
            {{ register_user_form.submit }}
            <input type="submit" value="SIGNUP" >

        </form>
    </div>

{% endblock %}

任何帮助都会很棒,谢谢!

感谢您的帮助。这真的解决了我遇到的大部分麻烦。 唯一不对的是我的形式。我忘了RegisterForm需要密码确认,所以我还补充说: {{ register_user_form.password_confirm(...) }}

并在我的主文件中包含app.config['SECRET_KEY'] = 'blah',以便注册不会遇到错误。

1 个答案:

答案 0 :(得分:2)

您无需为注册定义新路线。

在从signupform继承的RegisterForm课程中,您只需使用自定义逻辑覆盖validate方法,然后返回TrueFalse合适的。

在用于注册的html模板中,操作网址为{{ url_for_security('register') }}

同样适用于自定义登录表单 - 尽管网址操作为{{ url_for_security('login') }}