coding=utf-8
from flask import Flask, render_template, request, redirect, url_for, abort, make_response
1.创建flask框架 域名为:http://127.0.0.1:5000
app=Flask(__name__)
2. 返回字符串 访问:http://127.0.0.1:5000/ 页面显示该字符串
@ app.route('/')
def test():
return 'hello'
3. 返回字符串 访问: http://127.0.0.1:5000/index1 页面显示该字符串
@ app.route('/index1')
def test1():
return 'hello flask'
4. 将 name 以参数的形式传入方法,并返回,注意:与方法的参数相同
访问: http://127.0.0.1:5000/index2/lisi 页面显示lisi
@ app.route('/index2/<name>')
def test2(name):
return name
5. 返回页面 访问: http://127.0.0.1:5000/index3
@ app.route('/index3')
def test3():
return render_template('login.html')
6. 返回页面,并给页面传参 访问:http://127.0.0.1:5000/index3/msg
@ app.route('/index3/msg')
def test3_1():
# return render_template('login.html',参数名=参数值)
return render_template('login.html',msg='用户名或密码错误')
html中的代码: {{ xxx }} 取值语句
<!--接收单个参数-->
{{msg}}
7. 返回页面,并给页面传递参数列表 访问:http://127.0.0.1:5000/index3/list
@ app.route('/index3/list')
def test3_2():
# return render_template('login.html',参数名=参数值)
return render_template('login.html',list=['a','b','c','d','e'])
html中的代码: {% %} 控制语句
<!--接收参数列表-->
{% for i in list %}
{{i}}
{% endfor %}
此外:在HTML中设置变量 {% set 变量名= value %}
<!--设置单个值,并输出-->
{% set abc='hello' %}
{{abc}}
<!--设置列表并输出-->
{% set li=[1,2,3,4,5,6] %}
{% for num in li %}
{{ num }}
{% endfor %}
8. 页面的form表单提交的地址为/index4
接收用post方法提交的数据的方法,指定methods,默认为get
request.form['name值']
通过数据的name获取对应的值
@ app.route('/index4',methods=['GET','POST'])
def do_post():
uname=request.form['username']
pword=request.form['password']
return '欢迎:'+uname+'\t'+pword
表单代码:
<form action="/index4" method="post">
UserName:<input type="text" name="username"><br/>
PassWord:<input type="password" name="password"><br/>
<input type="submit" value="提交">
</form>
9. 接收get请求提交数据的方法
request.args['name值']
访问:http://127.0.0.1:5000/index5?username=zhangsan
通过参数名,获取参数值
@ app.route('/index5')
def do_get():
uname=request.args['username']
return '欢迎'+uname+'登录'
10 . 重定向
访问: http://127.0.0.1:5000/index6 跳转到:http://127.0.0.1:5000/index3
注意:url_for('路由对应的方法名')
@ app.route('/index6')
def re_url():
return redirect(url_for('test3'))
11. 返回状态码 访问: http://127.0.0.1:5000/index7 返回:500
@ app.route('/index7')
def code():
abort(500)
12. 返回一个自定义响应 访问:http://127.0.0.1:5000/set
@ app.route('/set')
def set():
response=make_response('返回一个自定义响应')
# 修改响应头
response.headers['cookie']='abc'
return response
服务启动
if __name__ == '__main__':
# 设置debug=1,使用debug运行,当代码被修改时,不需要再重启项目,会自行重启
app.run(debug=1)