1Flask介绍和安装
# Flask介绍
Flask是一个轻量级的可定制框架,使用Python语言编写,较其他同类型框架更为灵活、轻便、安全且容易上手。它可以很好地结合MVC模式进行开发,开发人员分工合作,小型团队在短时间内就可以完成功能丰富的中小型网站或Web服务的实现。另外,Flask还有很强的定制性,用户可以根据自己的需求来添加相应的功能,在保持核心功能简单的同时实现功能的丰富与扩展,其强大的插件库可以让用户实现个性化的网站定制,开发出功能强大的网站。
Flask是一个基于Python开发并且依赖jinja2模板(DTL)和Werkzeug WSGI(符合wsgi协议的web服务器,wsgiref)服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后触发Flask框架,开发人员基于Flask框架提供的功能对请求进行相应的处理,并返回给用户,如果要返回给用户复杂的内容时,需要借助jinja2模板来实现对模板的处理,即:将模板和数据进行渲染,将渲染后的字符串返回给用户浏览器。
# 安装 flask
pip install flask
# flask快速使用
from flask import Flask
app=Flask(__name__)
@app.route('/')
def index():
return 'hello flask'
if __name__ == '__main__':
app.run()
2 flask展示用户信息案例
from flask import Flask, render_template, request, redirect, session
app = Flask('web_site')
app.secret_key = 'national unification'
app.config.from_object('settings.DevelopmentConfig')
user_info = {
'1': {'name': 'tom', 'age': 20, 'detail': 'from usa'},
'2': {'name': 'kangkang', 'age': 22, 'detail': 'from CN'},
'3': {'name': 'jerry', 'age': 2, 'detail': 'from uk'},
}
from functools import wraps
def login_auth(func):
# @wraps(func)
def inner(*args, **kwargs):
if session.get('username') == 'kevin':
res = func(*args, **kwargs)
return res
return redirect('/login')
return inner
@app.route('/')
def index():
return 'hello flask'
@app.route('/home', endpoint='home')
@login_auth
def home():
return render_template('home.html', user_dic=user_info)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
else:
username = request.form.get('username')
password = request.form.get('password')
if username == 'kevin' and password == '1234':
session['username'] = 'kevin'
return redirect('/home')
return render_template('login.html', err='用户名或密码错误')
@app.route('/detail/<int:pk>', endpoint='detail')
@login_auth
def detail(pk):
pk = str(pk)
return render_template('detail.html', user_dic=user_info.get(pk))
if __name__ == '__main__':
app.run()
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body style="text-align: center">
<br><br><br>
<h2>登陆页面</h2>
<form action="" method="post">
<input type="text" name="username">
<br><br>
<input type="password" name="password">
<br><br>
<input type="submit" value="登陆">{{ err }}
</form>
</body>
</html>
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<br><br><br>
<h2>首页</h2>
<table>
{% for k,v in user_dic.items() %}
<tr>
<td>{{ k }}</td>
<td>{{ v.name }}</td>
<td>{{ v['name'] }}</td>
<td>{{ v.get('name') }}</td>
<td>{{ v.age }}</td>
<td><a href="/detail/{{ k }}">详情</a></td>
</tr>
{% endfor %}
</table>
</body>
</html>
detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<br><br><br>
<h2>详情</h2>
<table>
<tr>
<td>{{ user_dic.name}}</td>
<td>{{ user_dic.detail }}</td>
</tr>
</table>
</body>
</html>
3 Flask常见操作
# 响应
return 字符串 返回字符串
return render_template x渲染模板
return redirect('/login') 重定向
return jsonify(字典,列表) 返回json格式
# session
from flask importsession
session['']=赋值
4 配置文件配置
# flask配置文件有多种方式
# 方式一
app.config['DEBUG'] = True
# 方式二
app.secret_key = 'national unification'
app.debug = True
# 方式三:settings.py中(CONFIG_NAME=CONFIG_ATTR)
app.config.from_pyfile('settings.py')
print(app.config['CONFIG_NAME'])
# 方式四:settings.py中(类的方式)
app.config.from_object('settings.DevelopmentConfig')
# 方式五:
app.config.from_envvar("ENVIRON_VARIBLE")
# 方式六:
app.config.from_json("JSON_FILE_NAME")