Flask入门小项目 - 搭建极简博客(4)添加注册功能

目录:

完整程序点这

零、效果

注册成功后会看到数据库中users表中多了一条数据

一、修改app.py中的signup函数

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    error = None
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        if len(username) == 0:
            error = 'please input username'
        elif len(password) == 0:
            error = 'please input password'
        else:
            info = get_user_info(username)
            if info == 'username does not exist!':  # 用户名不存在,可以注册
                user = User(username=username, password=password)
                db.session.add(user)
                db.session.commit()
                flash('New user has been successfully added')
                return redirect(url_for('signup'))
            else:
                error = 'username already exists!'

    return render_template('signup.html', error=error)

二、signup.html

signup.html

{% extends "base.html" %}

{% block body %}
    <h2>Signup</h2>
    {% if error %}
          <p class=error><strong>Error:</strong> {{ error }}
    {% endif %}

    <form action="{{ url_for('signup') }}" method=post>

      <dl>
          <dt>Username:
          <dd><input type=text name=username>
          <dt>Password:
          <dd><input type=password name=password>
          <dd><input type=submit value=Signup>
      </dl>

    </form>
{% endblock %}

posted on 2020-04-10 12:59  HolaWorld  阅读(344)  评论(0编辑  收藏  举报

导航