Flask视图和url
url_for
进行反转,把函数名字转化成url
url_for('函数名字',参数1,参数2)
如果参数2不存在会以 ?参数2 的形式呈现
url_for的好处
- url_for会进行转码
- 修改了URL地址,对我们的代码影响不大,比硬编码方式更灵活
URL末尾的反斜线
有无反斜线是两个URL地址
指定HTTP方法
@app.route('xxx',methods=['请求方法'])
GET方法
request.args.get('xxx')
PORT方法
request.form.get('xxx')
重定向
return redirect(url_for('函数名',status))
- 301 永久重定向
- 302 临时重定向
Response响应
- 字符串
- re '字符串'
- 元组
- return '字符串','状态码'
- 字典
- return{'A':a}
- Response
return Response('字符串','状态码',mimetype='text/html')
- make_response
return make_response('字符串')
模板
模板渲染
先创建一个目录(templates),将模板文件放刀目录中
return render_template('模板文件名字')
模板传参
return render_template('index.html',username='逻辑教育')
{{ username }}
context = {
xxx:'xxx'
}
return render_template('index.html',context=context)
{{ context.xxx }}
{{ context[xxx] }}
return render_template('index.html',**context)
{{ xxx }}