1. 数据库连接池
使用 pymsql 链接数据库
导入:pip3 install dbutils
from dbutils.pooled_db import PooledDB
import pymysql
POOL = PooledDB(
creator=pymysql,
maxconnections=6,
mincached=2,
maxcached=5,
maxshared=3,
blocking=True,
maxusage=None,
setsession=[],
ping=0,
host='127.0.0.1',
port=3306,
user='???',
password='???',
database='???',
charset='utf8'
)
from flask import Flask
from pool import POOL
import pymysql
app = Flask(__name__)
app.debug = True
@app.route('/user')
def user():
conn = POOL.connection()
cursor = conn.cursor()
cursor.execute('select * from index_user')
print(cursor.fetchall())
conn.close()
return 'hello'
@app.route('/username')
def username():
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
database='???',
user='???',
password='???')
cursor = conn.cursor()
cursor.execute('select username from index_user')
print(cursor.fetchall())
return 'hello'
if __name__ == '__main__':
app.run()
2. wtfroms (了解)
其类似于 django 的 forms 组件,不过在 flask 中使用第三方 wtfroms 完成 forms 的功能。
安装:pip3 install wtforms
from flask import Flask,request,render_template
app = Flask(__name__)
from wtforms.fields import core
from wtforms import Form
from wtforms.fields import html5
from wtforms.fields import simple
from wtforms import validators
from wtforms import widgets
class LoginForm(Form):
name = simple.StringField(
label='用户名',
validators=[
validators.DataRequired(message='用户名不能为空.'),
validators.Length(min=6, max=18, message='用户名长度必须大于%(min)d且小于%(max)d')
],
widget=widgets.TextInput(),
render_kw={'class': 'form-control'}
)
pwd = simple.PasswordField(
label='密码',
validators=[
validators.DataRequired(message='密码不能为空.'),
validators.Length(min=8, message='用户名长度必须大于%(min)d'),
validators.Regexp(regex="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}",
message='密码至少8个字符,至少1个大写字母,1个小写字母,1个数字和1个特殊字符')
],
widget=widgets.PasswordInput(),
render_kw={'class': 'form-control'}
)
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
)
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, '羽毛球'))
def validate_pwd_confirm(self, field):
"""
自定义pwd_confirm字段规则,例:与pwd字段是否一致
:param field:
:return:
"""
if field.data != self.data['pwd']:
raise validators.StopValidation("密码不一致")
@app.route('/login',methods=['GET','POST'])
def login():
if request.method == 'GET':
form = LoginForm()
return render_template('login.html', form=form)
else:
form = LoginForm(formdata=request.form)
if form.validate():
print('用户提交数据通过格式验证,提交的值为:', form.data)
else:
print(form.errors)
return render_template('login.html', form=form)
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
form = RegisterForm(data={'gender': 2,'hobby':[1,]})
return render_template('register.html', form=form)
else:
form = RegisterForm(formdata=request.form)
if form.validate():
print('用户提交数据通过格式验证,提交的值为:', form.data)
else:
print(form.errors)
return render_template('register.html', form=form)
if __name__ == '__main__':
app.run()
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录</h1>
<form method="post">
<p>{{form.name.label}} {{form.name}} {{form.name.errors[0] }}</p>
<p>{{form.pwd.label}} {{form.pwd}} {{form.pwd.errors[0] }}</p>
<input type="submit" value="提交">
</form>
</body>
</html>
register.html
<!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>
3. 信号
Flask 信号,是由 signal 翻译过来的。
Flask框架中的信号基于 blinker,其主要就是让开发者可是在 Flask 请求过程中定制一些用户行为。 在某种情况下会触发某个函数执行( aop理念,面向切面编程的理念 ),例如在用户注册后统计用户的数量
安装:pip3 install blinker
3.1 内置信号
request_started = _signals.signal('request-started')
request_finished = _signals.signal('request-finished')
before_render_template = _signals.signal('before-render-template')
template_rendered = _signals.signal('template-rendered')
got_request_exception = _signals.signal('got-request-exception')
request_tearing_down = _signals.signal('request-tearing-down')
appcontext_tearing_down = _signals.signal('appcontext-tearing-down')
appcontext_pushed = _signals.signal('appcontext-pushed')
appcontext_popped = _signals.signal('appcontext-popped')
message_flashed = _signals.signal('message-flashed')
3.2 使用信号
from flask import Flask, render_template
from flask import signals
app = Flask(__name__)
app.debug = True
def render_before(*args, **kwargs):
print(args)
print(kwargs)
print('模板渲染前执行')
signals.before_render_template.connect(render_before)
@app.route('/home')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run()
3.3 自定义信号
from flask import Flask
from flask.signals import _signals
app = Flask(import_name=__name__)
x = _signals.signal('x')
def func(sender, *args, **kwargs):
print(sender)
print(args)
print(kwargs)
x.connect(func)
@app.route("/index")
def index():
x.send('123123', k1='v1')
return 'Index'
if __name__ == '__main__':
app.run()
4. 多app应用(了解)
在一个 flask 项目,可以支持多个 app 对象。
from flask import Flask
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple
app1 = Flask('app01')
app2 = Flask('app02')
@app1.route('/')
def home():
return "app1"
@app2.route('/')
def sec():
return "app2"
dm = DispatcherMiddleware(app1, {
'/sec': app2,
})
if __name__ == "__main__":
run_simple('localhost', 5000, dm)
5. flask-script
原本启动项目右键运行即可,若要以命令的方式,类似于 django 的 python3 manage.py runserver 命令可以使用 flask-script 实现。
安装:pip3 install flask-script
5.1 快速使用
from flask_script import Manager
app = Flask(__name__)
manager=Manager(app)
if __name__ == '__main__':
manager.run()
有可能会出现如下错误,由于 flask 的版本太高只需要将 flask 的版本降低即可
Traceback (most recent call last):
File "manage.py", line 3, in <module>
from flask_script import Manager
File "D:\python36\lib\site-packages\flask_script\__init__.py", line 15, in <module>
from flask._compat import text_type
ModuleNotFoundError: No module named 'flask._compat'
5.2 自定制命令
可以编一个功能,通过execl,把execl的数据存同步到某个数据表中得命令
from flask import Flask
from flask_script import Manager
app = Flask('__name__')
manager = Manager(app)
@manager.command
def dbinit():
"""
python manage.py dbinit
"""
print("数据库初始化完成")
@manager.option('-n', '--name', dest='name')
@manager.option('-a', '--age', dest='age')
def user(name, age):
"""
自定义命令(-n也可以写成--name)
执行: python manage.py user -n xwx -a 12
执行: python manage.py user --name xwx --age 12
"""
print(name, age)
@app.route('/index')
def index():
return "index"
if __name__ == "__main__":
manager.run()
|