一.简介
![image]()
二.flask安装
pip3 install flask
三.flask快速使用
from flask import Flask
app=Flask(__name__) # 实例化产生一个Flask对象
@app.route('/') # 当用户访问根路径
def index():
return 'hello world' # 浏览器返回hello world
if __name__ == '__main__':
app.run(port=8080) # 不写默认5000
四.flask配置文件
1.主要配置
flask中的配置文件是一个flask.config.Config对象(继承字典),默认配置为:
{
'DEBUG': get_debug_flag(default=False), 是否开启Debug模式
'TESTING': False, # 是否开启测试模式
'PROPAGATE_EXCEPTIONS': None,
'PRESERVE_CONTEXT_ON_EXCEPTION': None,
'SECRET_KEY': None,
'PERMANENT_SESSION_LIFETIME': timedelta(days=31),
'USE_X_SENDFILE': False,
'LOGGER_NAME': None,
'LOGGER_HANDLER_POLICY': 'always',
'SERVER_NAME': None,
'APPLICATION_ROOT': None,
'SESSION_COOKIE_NAME': 'session',
'SESSION_COOKIE_DOMAIN': None,
'SESSION_COOKIE_PATH': None,
'SESSION_COOKIE_HTTPONLY': True,
'SESSION_COOKIE_SECURE': False,
'SESSION_REFRESH_EACH_REQUEST': True,
'MAX_CONTENT_LENGTH': None,
'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),
'TRAP_BAD_REQUEST_ERRORS': False,
'TRAP_HTTP_EXCEPTIONS': False,
'EXPLAIN_TEMPLATE_LOADING': False,
'PREFERRED_URL_SCHEME': 'http',
'JSON_AS_ASCII': True,
'JSON_SORT_KEYS': True,
'JSONIFY_PRETTYPRINT_REGULAR': True,
'JSONIFY_MIMETYPE': 'application/json',
'TEMPLATES_AUTO_RELOAD': None,
}
2.flask配置方式
from flask import Flask,jsonify
app=Flask(__name__)
# 方式一:直接配置
app.secret_key='asdfasdf'
app.debug=True # 修改了代码,只需要保存,自动热加载
# 方式二:通过app.config字典,配置,这个字典中放了所有的配置
print(app.config)
app.debug=True
print(app.config)
app.config['DEBUG']=False # 都要大写
app.config['MYSQL_HOST']='127.0.0.1'
# 方式三:通过settings.py 配置文件--->用得少,django的方式
app.config.from_pyfile("settings.py")
print(app.config)
# 方式四:多套配置文件:开发环境,测试环境,线上环境 ,配置有差别
app.config.from_object("settings.DevelopmentConfig")
app.config.from_object("settings.ProductionConfig")
print(app.config)
# 方式五:服务(项目)多了,配置文件多了---》配置中心 nacos 阿波罗
m={}
m=request.get('ssss')
app.config.from_mapping(m)
@app.route('/')
def index():
# 方式一:相应头中,响应编码方式为 application/json
return jsonify({'name':"tony",'age':19})
# 方式二
res = {'name': "tony", 'age': 19}
import json
res=json.dumps(res)
return res
if __name__ == '__main__':
app.run()
五. flask 路由系统
1.路由本质
@app.router()--->本质是self.add_url_rule(),self就是flask对象app
2.注册方式
方式一:
@app.route('/index',methods=['GET'],endpoint='index')
方式二:
app.add_url_rule('/index',endpoint='index',methods=['GET'],view_func=index)
3.cbv
# 如果继承的是View,需要重写dispatch
# 如果继承的是MethodView,只需要写get,post。。方法即可
class HomeView(MethodView):
def get(self):
print(request.path)
return 'cbv的homeview'
# 添加路由
# name 是路由别名,跟endpoint一个作用,但是cbv必须传name
app.add_url_rule('/home',view_func=HomeView.as_view(name='home'))
4.app.add_url_rule参数
1 rule, URL规则, 可以使用转换器 <int:pk>
# @app.route('/detail/<int:nid>',methods=['GET'])
2 endpoint, 当前路由的别名,如果不传, 默认已函数名作为endpoint,如果函数名重名,就会有两个重名的地址,报错,主要用来反向解析
# endpoint = None, 名称,用于反向生成URL,即: url_for('名称')
# 多个视图函数,如果加同一个装饰器,如果不写endpoint,就会报错
3 view_func, 视图函数名称 如果是cbv 视图类.as_view(name='xx')
4 defaults = None, 默认值, 当URL中无参数,函数需要参数时,使用defaults = {'k': 'v'}为函数提供参数,就是django中的kwargs
5 methods = None, 允许的请求方式,如:["GET", "POST"]
6 strict_slashes = None
对URL最后的 / 符号是否严格要求
7 redirect_to = None, redirect_to='/home'
#重定向到指定地址
8 子域名访问
subdomain = None,
五.flask模板语法
1.渲染变量
6.1渲染变量
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table>
{% for k,v in user_dict.items() %}
<tr>
<td>{{k}}</td>
<td>{{v.name}}</td>
<td>{{v['name']}}</td>
<td>{{v.get('name')}}</td>
<td><a href="/detail/{{k}}">查看详细</a></td>
</tr>
{% endfor %}
</table>
</body>
</html>
2.变量的循环
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table>
{% for k,v in user_dict.items() %}
<tr>
<td>{{k}}</td>
<td>{{v.name}}</td>
<td>{{v['name']}}</td>
<td>{{v.get('name')}}</td>
<td><a href="/detail/{{k}}">查看详细</a></td>
</tr>
{% endfor %}
</table>
</body>
</html>
3.逻辑判断
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello World!</h1>
{% endif %}
</table>
</body>
</html>
总结:
1.flask的模板语法支持 (),[]
2. Markup等价django的mark_safe
3.extends,include一模一样
六.请求与相应
1.请求
# request.method 提交的方法
# request.args get请求提及的数据
# request.form post请求提交的数据
# request.values post和get提交的数据总和
# request.cookies 客户端所带的cookie
# request.headers 请求头
# request.path 不带域名,请求路径
# request.full_path 不带域名,带参数的请求路径
# request.script_root
# request.url 带域名带参数的请求路径
# request.base_url 带域名请求路径
# request.url_root 域名
# request.host_url 域名
# request.host 127.0.0.1:500
# request.files
# obj = request.files['the_file_name']
# obj.save('/var/www/uploads/'+secure_filename(f.filename))
2.响应
# return "字符串"
# return render_template('html模板路径',**{})
# return render_template('html模板路径',info=info)
# return redirect('/index.html') # 重定向
# return jsonify({'k1':'v1'}) # 返回json字符串
# url = url_for('login') # 反向解析
# return redirect(url)
# response = make_response(render_template('index.html'))
# response是flask.wrappers.Response类型
# response.delete_cookie('key')
# response.set_cookie('key', 'value')
# response.headers['X-Something'] = 'A value'
# return response
七.session
1.flask中使用session
# 使用session的前提设置一下密钥
app.secret_key="asdas" # 值随便写
设置值:session['username']='tony'
取值:session['username']
删除:session.pop('username', None)
2.django中session原理
# 响应走,在中间件的process_response中写的
1,生成一个随机的字符串 sdfads
2 往数据库存表
id key content expire
1 sdfads 数据内容(加密) 过期时间
3 写入cookie返回浏览器
response.set_cookie('sessionid',sdfads)
# 请求来了,在中间件的process_request中执行了
1 根据sessionid取出随机字符串
2 根据随机字符串去数据库查出content数据,解密
3 赋值个请求对象request.SESSION
4 你在视图函数中才能正常使用request.SESSION['name']取值,赋值,删除值
# 任何web框讲的session原理都是这个
3.flask中session原理
# 写入session流程
1 把sesion对象,当字典 转成字符串,使用秘钥加密
val = self.get_signing_serializer(app).dumps(dict(session))
2 写入cookie返回浏览器 session=加密的字符串
response.set_cookie(app.session_cookie_name,val )# 加密字符串
# 请求来了流程
1 根据sessionid取出加密字符串
val = request.cookies.get(app.session_cookie_name)
2 通过秘钥解密,组装成 session
data = s.loads(val, max_age=max_age)
self.session_class(data)
3 你在视图函数中才能正常使用session['name']取值,赋值,删除值
4.session源码的执行流程
-处理session,有个一个类SecureCookieSessionInterface(),有俩重要方法
-open_session:请求来了执行
1 根据sessionid取出加密字符串
val = request.cookies.get(app.session_cookie_name)
2 通过秘钥解密,组装成 session
data = s.loads(val, max_age=max_age)
self.session_class(data)
4 你在视图函数中才能正常使用session['name']取值,赋值,删除值
-save_session:请求走了执行
1 把sesion对象,当字典 转成字符串,使用秘钥加密
val = self.get_signing_serializer(app).dumps(dict(session))
2 写入cookie返回浏览器 session=加密的字符串
response.set_cookie(
app.session_cookie_name,
val, # 加密字符串
)
八.闪现(flash)
# 实际用途
-a页面出了错,重定向到b页面,b页面要把错误信息显示
# 本质:
如果在同一次请求中,放到request对象中即可
如果在不同请求中,放到session中,所以使用闪现一定配置秘钥
# 使用
设置:flash('美女')
获取:res=get_flashed_messages()
# 高级使用 按分类设置和获取
设置:
flash('美女',category='man')
flash('帅哥',category='wonmen')
获取:
res=get_flashed_messages(with_categories=True,category_filter=["man"])