URL的动态构建
接口模块
# 个人中心
@app.route('/panel/<username>')
def panel(username):
"""
URl的动态构建: 在调用接口的页面中,如:"url_for('panel', username="jackson")"
:param username:
:return:
"""
user = {"username": username, "email": "123@qq.com"}
return render_template('panel.html', user=user)
使用模板(template):在项目中创建templates模块,将所有的html/模版放入模块中
对应页面
其中“panel” 为定义的函数名
静态文件
- 创建一个“static” 包,将css/js文件放里面
- 在对应的页面,添加link标签
jinja2模板-template
示例-for循环遍历显示
<html lang="en">
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>
</body>
</html>
示例-if条件判断显示
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}
请求对象
method & form 属性
from flask import request
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if valid_login(request.form['username'],
request.form['password']):
return log_the_user_in(request.form['username'])
else:
error = 'Invalid username/password'
return render_template('login.html', error=error)
- 通过method属性可操作当前请求方法
- 通过使用form属性可获取表单数据
- 当form属性不存在这个键时,会引发一个KeyError
args属性 - 访问url参数
# 如:?key=value
searchword = request.args.get('key', '')
session
使用session模块,需要设置密钥
# 方式一
app.config['SECRET_KEY'] = os.urandom(24)
#方式二
app.secret_key = 'XXXXXX'
存储/读取/清除 session
类似于字典,以键值对的形式存储
# request.form.get 获取表单中的数据
session['username'] = request.form.get('username')
# 读取session
res = session['username'] # 若内容不存在,会报异常
res = session.get('key') # 若内容不存在,则返回None
# 清除指定的session
session.pop('username', None)
# 清除session中所有的数据
session.clear