标签:cli open stop lap option methods submit vco app应用
是一个让你的命令行支持自定义命令的工具,它为Flask程序添加一个命令行解释器。可以让我们的程序从命令行直接执行相应的程序(用于实现类似于django中 python3 manage.py runserver ...类似的命令)。
pip3 install flask-script
#1.manage.py文件中代码示例
from flask import Flask app = Flask(__name__) #1.导入模块 from flask_script import Manager #2.创建对象 manager = Manager(app) #4. 视图函数 @app.route(‘/‘) def index(): return ‘hello world‘ #5.启动代码 if __name__ == ‘__main__‘: manager.run()
#2.cmd窗口启动flask(只能通过此命令启动flask)
#如果代码不是在maage.py文件中就换成所在的文件名 python3 manage.py runserver 启动参数说明 1)-h, --host 指定主机 2)-p, --port 指定端口 3)-d 开启调试模式 4)-r 代码修改后自动加载 5)-?, --help 查看帮助信息
#1.mange.py文件
from flask import Flask app = Flask(__name__) #1.导入模块 from flask_script import Manager #2.创建对象 manager = Manager(app) #4. 视图函数 @app.route(‘/‘) def index(): return ‘hello world‘ # 第一种方式自定义命令 @manager.command def custom(arg): print(arg)
# 第二种方式自定义命令 @manager.option(‘-n‘,‘--name‘,dest=‘name‘) @manager.option(‘-a‘,‘--age‘,dest=‘age‘) def cmd(name,age): print(name,age) #5.启动代码 if __name__ == ‘__main__‘: manager.run()
#2.cmd窗口
# 1.第一种方式自定义命令 @manager.command def custom(arg): print(arg) # 启动方式:python3 manage.py 命令函数 参数 示例:python3 manage.py custom 1 #2. 第二种方式自定义命令 #@manager.option(‘-简写参数名‘,‘--全写参数名‘,dest=‘函数中的参数‘) # 注意函数中有几个参数就要几个装饰器 @manager.option(‘-n‘,‘--name‘,dest=‘name‘) @manager.option(‘-a‘,‘--age‘,dest=‘age‘) def cmd(name,age): print(name,age) # 启动方式:python3 manage.py 命令函数 简写或全写 参数1 简写或全写 参数2 示例:python3 manage.py cmd -n owen -a 18 或python3 manage.py cmd -name owen -age 18
flask的蓝图可以实现url的分发,当有多个app时也可以利用app进行url分发
#1.导入模块 from werkzeug.wsgi import DispatcherMiddleware from werkzeug.serving import run_simple from flask import Flask, current_app #2.创建多个app对象 app1 = Flask(‘app01‘) app2 = Flask(‘app02‘) app3 = Flask(‘ggggggggapp03‘) # 3.多app视图函数 @app1.route(‘/index1‘) def index1(): return "app01" @app2.route(‘/index2‘) def index2(): return "app2" @app3.route(‘/index3‘) def index3(): return "app3" #4.路由分发 dm = DispatcherMiddleware(app1, { #‘路由前缀‘:appd对象 ‘/app2‘: app2, ‘/app3‘: app3, }) """ http://localhost:5000/index1 http://localhost:5000/app2/index2 http://localhost:5000/app3/index3 """ # 5.启动 if __name__ == "__main__": run_simple(‘localhost‘, 5000, dm)
WTForms是一个支持多个web框架的form组件,主要用于对用户请求数据进行验证。
前提:安装模块
pip3 install wtforms
使用:
# 注册后端
from flask import Flask, render_template, request, redirect #导入wtform模块 from wtforms import Form from wtforms.fields import core from wtforms.fields import html5 from wtforms.fields import simple from wtforms import validators from wtforms import widgets app = Flask(__name__, template_folder=‘templates‘) app.debug = True class RegisterForm(Form): name = simple.StringField( #注释名 label=‘用户名‘, validators=[ validators.DataRequired() ], widget=widgets.TextInput(), render_kw={‘class‘: ‘form-control‘}, default=‘alex‘ ) pwd = simple.PasswordField( label=‘密码‘, validators=[ validators.DataRequired(message=‘密码不能为空.‘) ], #输入框的类型 widget=widgets.PasswordInput(), #样式 render_kw={‘class‘: ‘form-control‘} ) pwd_confirm = simple.PasswordField( label=‘重复密码‘, validators=[ validators.DataRequired(message=‘重复密码不能为空.‘), validators.EqualTo(‘pwd‘, message="两次密码输入不一致") ], widget=widgets.PasswordInput(), render_kw={‘class‘: ‘form-control‘} ) email = html5.EmailField( label=‘邮箱‘, validators=[ validators.DataRequired(message=‘邮箱不能为空.‘), validators.Email(message=‘邮箱格式错误‘) ], widget=widgets.TextInput(input_type=‘email‘), render_kw={‘class‘: ‘form-control‘} ) gender = core.RadioField( label=‘性别‘, choices=( (1, ‘男‘), (2, ‘女‘), ), coerce=int # “1” “2” 限制是int类型的 ) city = core.SelectField( label=‘城市‘, choices=( (‘bj‘, ‘北京‘), (‘sh‘, ‘上海‘), ) ) hobby = core.SelectMultipleField( label=‘爱好‘, choices=( (1, ‘篮球‘), (2, ‘足球‘), ), coerce=int ) favor = core.SelectMultipleField( label=‘喜好‘, choices=( (1, ‘篮球‘), (2, ‘足球‘), ), widget=widgets.ListWidget(prefix_label=False), option_widget=widgets.CheckboxInput(), coerce=int, default=[1, 2] ) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.favor.choices = ((1, ‘篮球‘), (2, ‘足球‘), (3, ‘羽毛球‘)) #把RegisterForm这个类里面的favor重新赋值 # 局部钩子校验2次密码是否一致 def validate_pwd_confirm(self, field): """ 自定义pwd_confirm字段规则,例:与pwd字段是否一致 :param field: :return: """ # 最开始初始化时,self.data中已经有所有的值 if field.data != self.data[‘pwd‘]: # raise validators.ValidationError("密码不一致") # 继续后续验证 raise validators.StopValidation("密码不一致") # 不再继续后续验证 @app.route(‘/register‘, methods=[‘GET‘, ‘POST‘]) def register(): if request.method == ‘GET‘: form = RegisterForm(data={‘gender‘: 2,‘hobby‘:[1,]}) # gender和hobby标签的默认值 return render_template(‘register1.html‘, form=form) else: form = RegisterForm(formdata=request.form) if form.validate(): print(‘用户提交数据通过格式验证,提交的值为:‘, form.data) else: print(form.errors) return render_template(‘register1.html‘, form=form) if __name__ == ‘__main__‘: app.run()
# 注册前端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用户注册</h1> <form method="post" novalidate style="padding:0 50px"> {% for field in form %} <p>{{field.label}}: {{field}} {{field.errors[0] }}</p> {% endfor %} <input type="submit" value="提交"> </form> </body> </html>
Flask:flask-script;多app应用;wtforms;sqlchmy
标签:cli open stop lap option methods submit vco app应用
原文地址:https://www.cnblogs.com/tfzz/p/11863366.html