美文网首页
Flask实战之register&login

Flask实战之register&login

作者: whenitsallover | 来源:发表于2018-04-18 23:20 被阅读0次
    创建flask项目

    连接MySQL数据库,创建pythonprogramming数据库

    CREATE TABLE users (uid INT(11) AUTO_INCREMENT PRIMARY KEY, username VARCHAR(20), password VARCHAR(100), email VARCHAR(50), settings VARCHAR(32500), tracking VARCHAR(32500), rank INT(3));
    

    在项目的根目录下创建connection.py

    
    import MySQLdb
    
    def connection():
        conn = MySQLdb.connect(host="localhost",
                               user = "root",
                               passwd = "oops",
                               db = "pythonprogramming")
        c = conn.cursor()
    
        return c, conn
    
    

    flask-tutorial.py

    from flask import Flask,render_template,request,flash,session,redirect,url_for
    
    from dbconnect import connection
    from wtforms import Form,StringField,PasswordField,validators,BooleanField
    from passlib.hash import sha256_crypt
    from MySQLdb import escape_string as thwart
    import gc
    
    
    app = Flask(__name__)
    app.secret_key = 'asdfsdfsdf'
    
    @app.route('/welcome')
    def welcome():
        return render_template('welcome.html')
    
    class RegistrationForm(Form):
        username = StringField('Username', [validators.Length(min=4, max=20)])
        email = StringField('Email Address', [validators.Length(min=6, max=50)])
        password = PasswordField('New Password', [
            validators.required(),
            validators.EqualTo('confirm', message='Passwords must match')
        ])
        confirm = PasswordField('Repeat Password')
        accept_tos = BooleanField('I accept the Terms of Service and Privacy Notice (updated Jan 22, 2015)',
                                  [validators.required()])
    
    
    @app.route('/register/', methods=["GET", "POST"])
    def register_page():
        try:
            form = RegistrationForm(request.form)
    
            if request.method == "POST" and form.validate():
                username = form.username.data
                email = form.email.data
                password = sha256_crypt.encrypt((str(form.password.data)))
                c, conn = connection()
                x = c.execute("SELECT * FROM users WHERE username = (%s)",
                              (thwart(username),))
                if int(x) > 0:
                    flash("That username is already taken, please choose another")
                    return render_template('register.html', form=form)
    
                else:
                    c.execute("insert into users (username, password, email, tracking) values (%s, %s, %s, %s)",
                              (thwart(username,), thwart(password,), thwart(email,),
                               thwart("/login/",)))
    
                    conn.commit()
                    flash("Thanks for registering!")
                    c.close()
                    conn.close()
                    gc.collect()
    
                    session['logged_in'] = True
                    session['username'] = username
    
                    return redirect(url_for('welcome'))
    
            return render_template("register.html", form=form)
    
        except Exception as e:
            return (str(e))
    
    @app.route('/login/', methods=["GET", "POST"])
    def login_page():
        error = ''
        try:
            c, conn = connection()
    
            if request.method == "POST":
    
                c.execute("select * from users where username = (%s)",
                          (thwart(request.form['username']),))  ##
                data = c.fetchone()[2]
    
                if sha256_crypt.verify(request.form['password'], data):
                    session['logged_in'] = True
                    session['username'] = request.form['username']
    
                    flash("You are now logged in")
                    return redirect(url_for("welcome"))
    
                else:
                    error = "Invalid credentials, try again."
    
            gc.collect()
    
    
            return render_template("login.html", error=error)
    
        except Exception as e:
            # flash(e)
            print(e)
            error = "Invalid credentials, try again."
            return render_template("login.html", error=error)
    
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    _formhelpers.html

    {% macro render_field(field) %}
      <dt>{{ field.label }}
      <dd>{{ field(**kwargs)|safe }}
      {% if field.errors %}
        <ul class=errors>
        {% for error in field.errors %}
          <li>{{ error }}</li>
        {% endfor %}
        </ul>
      {% endif %}
      </dd>
    {% endmacro %}
    

    register.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                {% from "_formhelpers.html" import render_field %}
                <form method=post>
                    <dl>
                        {{ render_field(form.username) }}
                        {{ render_field(form.email) }}
                        {{ render_field(form.password) }}
                        {{ render_field(form.confirm) }}
                        {{ render_field(form.accept_tos) }}
                    </dl>
                    <p><input type=submit value=Register>
                </form>
            </div>
        </div>
    </div>
    
    </body>
    </html>
    

    Once we have the information in the form, the next thing we want to do is connect to the database. Now we don't want to have two users with the same username, so we first want to see if that username already exists. If it does, then we want to tell them that username already exists, and let them try again.

    If the username does not already exist, and we've made it to this point, that means we have a unique username, passwords that match, and an email, ready to insert into our database.

    So we insert to the database, flash a message to the user thanking them to register, and you're done.

    When you're all set with your insertions, then you need to make sure you always run a conn.commit(), which is "save" your changes to the database. If you forget to do this, then your changes will not be saved.

    Finally, we use gc.collect() to help keep memory waste down.

    Notice also that we happen to log in our user after they register, using the flask session functionality.

    login.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
    </head>
    <body>
    <h1 style="text-align: center;color: crimson;">登录聚界面</h1>
    <div class="container" style="margin-top:50px">
        <div class="rol">
            <div class="col-md-6 col-md-offset-3">
                <form action="" class="form-inline" method="post">
                    <input type="text" class="form-control" placeholder="Username" name="username"
                           value="{{ request.form.username }}">
                    <input type="password" class="form-control" placeholder="Password" name="password"
                           value="{{ request.form.password }}">
                    <input class="btn btn-default" type="submit" value="登录">
                </form>
                {{ error }}
            </div>
        </div>
    </div>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:Flask实战之register&login

          本文链接:https://www.haomeiwen.com/subject/llqikftx.html