H
H
hardwellZero2015-03-05 22:58:38
Flask
hardwellZero, 2015-03-05 22:58:38

What's wrong with Flask registration?

Another question about registration on Flask.
I'm trying to write a registration using Flask, jinja2, WTForms, SQLAlchemy.
The code from the article on Habré is taken as a basis, where authorization occurs through OpenID.
Need help. Bring it all to mind, because my knowledge is not enough, and pointless picking in the code will lead to nothing. IMPORTANT! I do not ask you to write everything for me, I ask you to clearly explain. I'm here to understand and do, not for pieces of code. Thank you for your attention.
views.py

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        return redirect('/index')
    return render_template('login.html',
                           title='Sign In',
                           form=form)


forms.py
from flask.ext.wtf import Form
from wtforms import StringField, BooleanField, PasswordField
from wtforms.validators import DataRequired
class LoginForm(Form):
    username = StringField('username', validators=[DataRequired()])
    password = PasswordField('password', validators=[DataRequired()])

login.html
<form method="POST" action="/login">
        <div>{{ form.username.label }}: {{ form.username(class="css_class") }}</div>
        {% if form.username.errors %}
            <ul class="errors">{% for error in form.username.errors %}<li>{{ error }}</li>{% endfor %}</ul>
        {% endif %}

        <div>{{ form.password.label }}: {{ form.password() }}</div>
        {% if form.password.errors %}
            <ul class="errors">{% for error in form.password.errors %}<li>{{ error }}</li>{% endfor %}</ul>
        {% endif %}
        <input type="submit" value="Go">
    </form>

models.py
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    nickname = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    posts = db.relationship('Post', backref='author', lazy='dynamic')

    def __repr__(self):
        return '<User %r>' % (self.nickname)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
German Jet, 2015-03-05
@hardwellZero

Briefly, after checking the validation, you take the username and password from the form, make a request for them to the database, and if such a user with such a password exists, use the login_user () method from Flask-login

# -*- coding: utf-8 -*-
from flask import request, render_template, flash, g, session, redirect, url_for
from flask.ext.login import login_user, logout_user, current_user, login_required
from app import db
from app.models import User
from app.forms import LoginForm
    
@app.route('/', methods=['GET', 'POST'])
def index():
    form = LoginForm()
    if form.validate_on_submit():
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username, password=password).first()
        if user is None:
            flash(u'Неверный логин или пароль', 'error')
            return redirect("/")
        login_user(user)
        return redirect("/")
    return render_template("main/main.html", 
        form = form)

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

models.py
from app import db

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    username = db.Column(db.String(120), unique=True)
    password = db.Column(db.String(120))

    def __init__(self, name, username, password):
        self.name = name
        self.username = username
        self.password = password

    def is_authenticated(self):
        return True
   
    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self.id)

    def __repr__(self):
        return self.name

template
{% with messages = get_flashed_messages() %}
  {% if messages %}
  <div class="flash">
  {% for message in messages %}
      {{ message }}
  {% endfor %}
  </div>
  {% endif %}
{% endwith %}

<form method="POST" action="/login">
    <div>{{ form.username.label }}: {{ form.username(class="css_class") }}</div>
    {% if form.username.errors %}
        <ul class="errors">{% for error in form.username.errors %}<li>{{ error }}</li>{% endfor %}</ul>
    {% endif %}

    <div>{{ form.password.label }}: {{ form.password() }}</div>
    {% if form.password.errors %}
        <ul class="errors">{% for error in form.password.errors %}<li>{{ error }}</li>{% endfor %}</ul>
    {% endif %}
    <input type="submit" value="Go">
</form>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question