1、定义路由
@app.route(‘/‘)是装饰器,定义如下:
app.route(rule, options)
rule参数:是绑定URL与函数。
options参数:是可选参数。
2、run() 函数来让应用运行在本地服务器上。定义如下 :
app.run(host, port, debug, options)
host:服务器主机名,默认是127.0.0.1 (localhost),如果设置0.0.0.0可以在本机之外访问。
port:主机端口,默认是5000。
debug:调试模式,默认是false;如果设置true,服务器会在代码修改后自动重新载入。
options:可选参数。
1 from flask import Flask 2 3 app=Flask(__name__) #创建1个Flask实例 4 5 @app.route(‘/‘) #路由系统生成 视图对应url,1. decorator=app.route() 2. decorator(first_flask) 6 def first_flask(): #视图函数 7 return ‘Hello World‘ #response 8 9 10 if __name__ == ‘__main__‘: 11 app.run() #启动socket
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <h1>登录</h1> 9 <form method="post" novalidate> 10 <!--<input type="text" name="name">--> 11 <p>{{form.name.label}} {{form.name}} {{form.name.errors[0] }}</p> 12 13 <!--<input type="password" name="pwd">--> 14 <p>{{form.pwd.label}} {{form.pwd}} {{form.pwd.errors[0] }}</p> 15 <input type="submit" value="提交"> 16 </form> 17 </body> 18 </html> 19 20 login.html
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 from flask import Flask, render_template, request, redirect 4 from wtforms import Form 5 from wtforms.fields import core 6 from wtforms.fields import html5 7 from wtforms.fields import simple 8 from wtforms import validators 9 from wtforms import widgets 10 11 12 app=Flask(__name__,template_folder=‘templates‘) #知道模板文件 13 app.debug=True 14 15 #登录验证实例 16 class LoginForm(Form): 17 18 #不同的字段 内部包含正则表达式 html5.EmailField | html5.DateTimeField... 19 name=simple.StringField( 20 label=‘用户名‘, 21 validators=[ #验证规则和错误提示信息 22 validators.DataRequired(message=‘用户名不能为空.‘), 23 validators.Length(min=6, max=18, message=‘用户名长度必须大于%(min)d且小于%(max)d‘) 24 ], 25 widget=widgets.TextInput(), #前端页面显示的插件.TextArea 26 render_kw={‘class‘: ‘form-control‘} #设置form标签的class信息 27 28 ) 29 30 # 不同的字段 内部包含正则表达式 html5.EmailField | html5.DateTimeField... 31 pwd = simple.PasswordField( 32 label=‘密码‘, 33 validators=[ 34 validators.DataRequired(message=‘密码不能为空.‘), 35 validators.Length(min=8, message=‘用户名长度必须大于%(min)d‘), 36 #自定义验证规则 37 validators.Regexp(regex="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}", 38 message=‘密码至少8个字符,至少1个大写字母,1个小写字母,1个数字和1个特殊字符‘) 39 40 ], 41 widget=widgets.PasswordInput(), 42 render_kw={‘class‘: ‘form-control‘} 43 ) 44 45 46 47 @app.route(‘/login/‘, methods=[‘GET‘, ‘POST‘]) 48 def login(): 49 if request.method == ‘GET‘: 50 form = LoginForm() #实例化 form验证类 51 return render_template(‘login.html‘, form=form) 52 else: 53 form = LoginForm(formdata=request.form) 54 if form.validate(): #判断是否验证成功? 55 print(‘用户提交数据通过格式验证,提交的值为:‘, form.data) 56 else: 57 print(form.errors) 58 return render_template(‘login.html‘, form=form) 59 60 if __name__ == ‘__main__‘: 61 app.run()
用户注册页面
1 #用户注册 2 from flask import Flask, render_template, request, redirect 3 from wtforms import Form 4 from wtforms.fields import core 5 from wtforms.fields import html5 6 from wtforms.fields import simple 7 from wtforms import validators 8 from wtforms import widgets 9 10 app = Flask(__name__, template_folder=‘templates‘) 11 app.debug = True 12 13 14 15 class RegisterForm(Form): 16 name = simple.StringField( 17 label=‘用户名‘, 18 validators=[ 19 validators.DataRequired() 20 ], 21 widget=widgets.TextInput(), 22 render_kw={‘class‘: ‘form-control‘}, 23 default=‘张根‘ #设置input标签中默认值 24 ) 25 26 pwd = simple.PasswordField( 27 label=‘密码‘, 28 validators=[ 29 validators.DataRequired(message=‘密码不能为空.‘) 30 ], 31 widget=widgets.PasswordInput(), 32 render_kw={‘class‘: ‘form-control‘} 33 ) 34 35 pwd_confirm = simple.PasswordField( #第二次输入密码 36 label=‘重复密码‘, 37 validators=[ 38 validators.DataRequired(message=‘重复密码不能为空.‘), 39 validators.EqualTo(‘pwd‘, message="两次密码输入不一致") #验证2次输入的密码是否一致? 40 ], 41 widget=widgets.PasswordInput(), 42 render_kw={‘class‘: ‘form-control‘} 43 ) 44 45 email = html5.EmailField( 46 label=‘邮箱‘, 47 validators=[ 48 validators.DataRequired(message=‘邮箱不能为空.‘), 49 validators.Email(message=‘邮箱格式错误‘) 50 ], 51 widget=widgets.TextInput(input_type=‘email‘), #生成email input标签 52 render_kw={‘class‘: ‘form-control‘} 53 ) 54 55 gender = core.RadioField( 56 label=‘性别‘, 57 choices=( #choice radio选项 58 (1, ‘男‘), 59 (2, ‘女‘), 60 ), 61 coerce=int #讲用户提交过来的 ‘4‘ 强制转成 int 4 62 ) 63 city = core.SelectField( 64 label=‘城市‘, 65 choices=( 66 (‘bj‘, ‘北京‘), 67 (‘sh‘, ‘上海‘), 68 ) 69 ) 70 71 hobby = core.SelectMultipleField( #select 下拉框多选框 72 label=‘爱好‘, 73 choices=( 74 (1, ‘篮球‘), 75 (2, ‘足球‘), 76 ), 77 coerce=int 78 ) 79 80 favor = core.SelectMultipleField( 81 label=‘喜好‘, 82 choices=( 83 (1, ‘篮球‘), 84 (2, ‘足球‘), 85 ), 86 widget=widgets.ListWidget(prefix_label=False), #生成Checkbox 多选框 87 option_widget=widgets.CheckboxInput(), 88 coerce=int, 89 default=[1, 2] 90 ) 91 92 def __init__(self, *args, **kwargs): #重写form验证类的__init__方法可以实时同步数据中数据 93 super(RegisterForm, self).__init__(*args, **kwargs) 94 self.favor.choices = ((1, ‘篮球‘), (2, ‘足球‘), (3, ‘羽毛球‘)) 95 96 97 def validate_pwd_confirm(self, field): #wtforms验证 钩子函数 98 """ 99 自定义pwd_confirm字段规则,例:与pwd字段是否一致 100 :param field: 101 :return: 102 """ 103 # 最开始初始化时,self.data中已经有所有的值 104 105 if field.data != self.data[‘pwd‘]: 106 # raise validators.ValidationError("密码不一致") # 继续后续验证 107 raise validators.StopValidation("密码不一致") # 不再继续后续验证 108 109 110 @app.route(‘/register/‘, methods=[‘GET‘, ‘POST‘]) 111 def register(): 112 if request.method == ‘GET‘: 113 form = RegisterForm(data={‘gender‘: 1}) #默认值 114 return render_template(‘register.html‘, form=form) 115 else: 116 form = RegisterForm(formdata=request.form) 117 if form.validate(): 118 print(‘用户提交数据通过格式验证,提交的值为:‘, form.data) 119 else: 120 print(form.errors) 121 return render_template(‘register.html‘, form=form) 122 123 124 125 if __name__ == ‘__main__‘: 126 app.run() 127 app02.py
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <h1>用户注册</h1> 9 <form method="post" novalidate style="padding:0 50px"> 10 {% for item in form %} 11 <p>{{item.label}}: {{item}} {{item.errors[0] }}</p> 12 {% endfor %} 13 <input type="submit" value="提交"> 14 </form> 15 </body> 16 </html> 17 18 register.html
原文:https://www.cnblogs.com/guohad/p/13399206.html