search
HomeBackend DevelopmentPython TutorialDetailed example of user registration function development (python)

The birth of a web application based on flask is the fifth article. This article mainly introduces the development of user registration function. It has certain reference value. Interested friends can refer to it.

The roles are divided below There are two types, ordinary users and administrator users. At least for ordinary users, it is not advisable to directly modify the DB. A user registration function is required. The development of user registration will begin below.

User Table

First of all, think about what information users need to provide when registering: user name, password, nickname, email, birthday, gender, self Introduction, let’s modify the user model according to this information:

class User(db.Model):
 __tablename__="users"
 id=db.Column(db.Integer,primary_key=True)
 username=db.Column(db.String(50),unique=True,index=True)
 password=db.Column(db.String(50))
 nickname=db.Column(db.String(50))
 email=db.Column(db.String(100))
 birthday=db.Column(db.DateTime)
 gender=db.Column(db.Integer)
 remark=db.Column(db.String(200))
 role_id=db.Column(db.Integer,db.ForeignKey("roles.id"))

Then use the script to modify the db

python default.py db migrate -m "修改用户表"

After pressing Enter, the interface displays the content:

Then make changes to the db difference

python default.py db upgrade

Now look at the table structure in the db:

has been modified successfully

Registration interface

Then create a new register.html template and set the login form:

{% extends "base.html"%}
{% block content %} <!--具体内容-->
<p class="container">
 <p class="row"></p>
 <p class="row">

  <p>
   <p class="page-header">
    <h1 id="欢迎您注册">欢迎您注册</h1>
   </p>
   {% for message in get_flashed_messages() %}
   <p class="alert alert-warning">
    <button type="button" class="close" data-dismiss="alter">&times</button>
    {{message}}
   </p>
   {% endfor %}
   <form method="post">
    <p class="form-group">
    <label for="username">用户名</label>
    <input type="text" class="form-control" name="username" id="username" placeholder="请输入用户名">
    </p>
    <p class="form-group">
    <label for="passworld">密码</label>
    <input type="password" class="form-control" name="password" id="passworld" placeholder="请输入密码">
    </p>
    <p class="form-group">
    <label for="email">昵称</label>
    <input type="email" class="form-control" name="nickname" id="nickname" placeholder="请输入昵称">
    </p>
    <p class="form-group">
    <label for="birthday">生日</label>
    <input type="date" class="form-control" name="birthday" id="birthday" placeholder="请输入生日">
    </p>
    <p class="form-group">
    <label >性别</label>
    <label class="form-control">
     <input type="radio" name="gender" value="0" id="gender0"><label for="gender0">男</label>
     <input type="radio" name="gender" value="1" id="gender1"><label for="gender1">女</label>
    </label>
    </p>
    <p class="form-group">
    <label for="email">电子邮箱</label>
    <input type="email" class="form-control" name="email" id="email" placeholder="请输入电子邮箱">
    </p>
    <button type="submit" class="btn btn-default">登录</button>
   </form>
  </p>
 </p>
</p>
{% endblock %}

Then add the register route in the default.py file, the code is:

@app.route("/register",methods=["GET"])
def register():
 return render_template("/register.html")

The running interface is normal, and then add post routing:

@app.route("/register",methods=["Post"])
def registerPost():
 user=User();
 user.username=request.form.get("username","")
 user.password = request.form.get("password", "")
 user.birthday = request.form.get("birthday", "")
 user.email = request.form.get("email", "")
 user.gender = request.form.get("gender", "")
 user.nickname = request.form.get("nickname", "")
 user.role_id = 1 #暂时约定公开用户角色为1

 #判断,其中用户名,密码,昵称不能为空
 if(len(user.username.strip())==0):
  flash("用户名不能为空")
  return render_template("/register.html")
 if(len(user.password.strip())==0):
  flash("用户密码不能为空")
  return render_template("/register.html")
 if (len(user.nickname.strip()) == 0):
  flash("用户昵称不能为空")
  return render_template("/register.html")
 db.session.add(user);
 flash("您已注册成功")
 return render_template("/register.html")

The code is a bit verbose and not beautiful, but the basic intention can be expressed clearly and the function can be realized, but now the problem is coming, join me If you add a new field, you need to modify three codes (html, form.get, verification), and especially the html needs to be modified, and the html part is not verified. If client verification is added, more modifications will be needed. So is there a tool for optimizing forms? The answer is of course, it’s wtf’s turn.

Introducing the WTF form framework

As before, you first need to install the plug-in.

pip3.6 install flask-wtf

Then introduce the required packages

from flask.ext.wtf import Form
from wtforms import StringField,PasswordField,SubmitField,RadioField
from wtforms.validators import DataRequired,EqualTo,Length

Create a form RegisterForm below:

class RegisterForm(Form):
 username = StringField("请输入用户名", validators=[DataRequired()])
 password = PasswordField("请输入密码", validators=[DataRequired()])
 repassword=PasswordField("确认密码", validators=[EqualTo("password")])
 nickname= StringField("昵称")
 birthday= DateField("出生日期")
 email= StringField("邮箱地址", validators=[Email()])
 gender= RadioField("性别", choices=[("0", "男"), ("1", "女")], default=0)
 remark= TextAreaField("自我简介")
 submit=SubmitField("提交")

Modify the register.html template:

{% extends "base.html"%}
{% block content %} <!--具体内容-->
{% import "bootstrap/wtf.html" as wtf %} <!--导入bootstrap模板 -->
<p class="container">
 <p class="row"></p>
 <p class="row">

  <p>
   <p class="page-header">
    <h1 id="欢迎您注册">欢迎您注册</h1>
   </p>
   {% for message in get_flashed_messages() %}
   <p class="alert alert-warning">
    <button type="button" class="close" data-dismiss="alter">&times</button>
    {{message}}
   </p>
   {% endfor %}
   {{ wtf.quick_form(form)}} <!--创建表单-->
  </p>
 </p>
</p>
{% endblock %}

Execute and output the results :

Aou, an error was reported, see what error the output is:

Pay attention to the red line, it is CSRF Error, the concept of CSRF can be directly linked to Baidu. Once you know the problem, it is actually easy to modify. Adding a secret key to the framework can effectively prevent it. Add a line to default.py:

app.config[&#39;SECRET_KEY&#39;] = "Niu_blog String"

The secret key string can be customized

Then run it again, and the interface will appear:

and contains the verification style for verifying bootstrap, then continue The registration function has been completed by transforming default.py

@app.route("/register",methods=["GET","POST"])
def register():
 form=RegisterForm()
 if form.validate_on_submit():
  user=User()
  user.username=form.username.data
  user.password=form.password.data
  user.birthday=form.birthday.data
  user.email=form.email.data
  user.gender=form.gender.data
  user.nickname=form.nickname.data
  user.role_id=1   #暂时约定公开用户角色为1
  db.session.add(user)
 return render_template("/register.html",form=form)

Note that the registerPost method has been deleted at this time

Let’s run and test it

Click to submit:

Ao, why is the date format wrong? You have to read this from the source code:

class DateField(DateTimeField):
 """
 Same as DateTimeField, except stores a `datetime.date`.
 """
 def __init__(self, label=None, validators=None, format=&#39;%Y-%m-%d&#39;, **kwargs):
  super(DateField, self).__init__(label, validators, format, **kwargs)

 def process_formdata(self, valuelist):
  if valuelist:
   date_str = &#39; &#39;.join(valuelist)
   try:
    self.data = datetime.datetime.strptime(date_str, self.format).date()
   except ValueError:
    self.data = None
    raise ValueError(self.gettext(&#39;Not a valid date value&#39;))

This is the source code of wtforms field, located at line 745 of /wtforms/fields/core.py. You can see that the date format supported here is year-month- Japanese format, the format is relatively strict, and the text box does not use HTML5 date but ordinary text. The solution will be discussed later. For now, modify the input to 1988-2-5, and then click Submit:


Note that after the code is submitted successfully, it still returns to this page and injects content, so there is no problem with the display. Take a look at the db:

The record enters the db normally and the function is completed.

Improve the login page

Let’s transform the login page. First create the login form:

class LoginForm(Form):
 username=StringField("请输入用户名",validators=[DataRequired()])
 password=PasswordField("请输入密码")
 submit=SubmitField("登录")

Modify the login template page:

{% extends "base.html"%}
{% import "bootstrap/wtf.html" as wtf %}
{% block content %} <!--具体内容-->
<p class="container">
 <p class="row"></p>
 <p class="row">

  <p class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3">
   <p class="page-header">
    <h1 id="欢迎您登陆">欢迎您登陆</h1>
   </p>
   {% for message in get_flashed_messages() %}
   <p class="alert alert-warning">
    <button type="button" class="close" data-dismiss="alter">&times</button>
    {{message}}
   </p>
   {% endfor %}
   {{ wtf.quick_form(form)}}
  </p>
 </p>
</p>
{% endblock %}

Modify routing method:

@app.route("/login",methods=["GET","POST"])
def login():
 form=LoginForm()
 if form.validate_on_submit():
  username = form.username.data
  password = form.password.data
  user = User.query.filter_by(username=username, password=password).first()
  if user is not None:
   session["user"] = username
   return render_template("/index.html", name=username, site_name=&#39;myblog&#39;)
  else:
   flash("您输入的用户名或密码错误")
   return render_template("/login.html",form=form) # 返回的仍为登录页
 return render_template("/login.html",form=form)

Restart the service, run the program, enter zhangji and 123, and successfully log in to the homepage

Return to the homepage

Now the home page is completely white with no content. A normal light blog should display the post button, followed articles, etc. after logging in, but the login status must be recorded first, which will be explained in the next chapter.

The above is the detailed content of Detailed example of user registration function development (python). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)