flask笔记02
url_for
这个函数可以返回指定的函数的url路由地址
print(url_for('函数名字',参数))
这是它的写法,‘ ’ 里面是要返回url的函数名字
我们先写两个简单的视图函数
from flask import Flask,url_for
app = Flask(__name__)
@app.route('/')
def root():
return 'hello world'
@app.route('/net/<int:aid>')
def net(aid):
return f'net->{aid}'
if __name__ == '__main__':
app.run()
然后我们在root函数中添加返回net函数的路由的url_for函数
@app.route('/')
def root():
print(url_for('net',aid=1))
return 'hello world'
确实返回了对应的路由地址
使用url_for的优点
1,如果修改了url地址(app.route里的路径),但只要你没修改对应的函数名字,用url_for就会很方便,因为它的参数是函数的名字,所以不用到处去修改url地址
2,url_for()会自动转义一些特殊字符和unicode字符,使用方便
如我们在net中插入url_for函数,然后指定参数为’\n’,我们看看打印的结果
@app.route('/net/<int:aid>')
def net(aid):
print(url_for('root',next='\n'))
return f'net->{aid}'
刷新后访问http://127.0.0.1:5000/net/1
/?next=%0A
可以看到url_for直接将’\n’进行了转码
post请求
http有多种请求,其中最常用的是get,和post请求。
上文的请求格式都是get请求
我们用postman发送一个key为name,value为chen的请求,要想它能正常运行,代码要如下编写
from flask import Flask,url_for,request
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def hello_world():
print(request.form.get('name'))
return 'hello world'
if __name__ == '__main__':
app.run(debug=True)
methons的列表中显示的是这条装饰语句装饰的函数,可以使用的访问方法。
它默认是只有‘GET’方法,这里我们设置它还可以用post方法。
request后面换成了form因为post是存在form里的
重定向
重定向有两种,分为临时重定向(状态码:302)和永久重定向(装态码:301)
假设,我们在访问淘宝网时,假设你看中了一个商品,点击购买时,并不会跳转到购买页面,而是检测你是否登录了账号,如果没有,就会跳转到登录页面。
这就是临时重定向。
一些大型的网站绝对都不止有一个域名,但是无论你访问那一个都是跳转到一个网址上。
这既是永久重定向。
下面我们用代码实现一个重定向
from flask import Flask,request,url_for,redirect
app = Flask(__name__)
@app.route('/')
def root():
return "hello world"
@app.route('/net/')
def net():
num = request.args.get('num')
if num:
return num
else:
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
这段代码的功能是访问127.0.0.1:5000显示helloworld,
访问127.0.0.1:5000/net/?num=x 显示x
访问127.0.0.1:5000/net/XXXXX
只要net/后面没有按格式输入就是跳转到127.0.0.1:5000显示helloworld。
简单讲一下原理。
用get获取到输入的参数存到num中
然后判断有没有接收到,如果接收到了,显示接受的数据
如果没有接受到,就说明输入格式不正确,那就是跳转会root函数的路径
不过查看审查元素可以看到它的状态码是302,是临时重定向
想要永久重定向也很简单。
只需要改一句代码就可以了
return redirect(url_for('root'),code=301)
(其中的url_for是个小升级,这样以后改url路径很方便)
响应
实际上,上面的函数里面的return后面的就是响应
响应是有格式要求的
The return type must be a string, dict, tuple, Response instance, or WSGI callable
from flask import Flask
app1 = Flask(__name__)
@app1.route('/next/')
def menu():
return {'test':'try'}
if __name__ == '__main__':
app1.run(debug=True)
换成
return ('test','try')
它只显示元组的第一个元素
再换
return 'test',200
这个元组的第二个参数是可以改变状态码的
return 'test',400
而当我们想要更详细的设置参数时就可以用到“Response”模块了
return Response('test',status=200,mimetype='text/html')
实际上,打开这个模块我们可以看到所有的能设置的参数
flask模块
简单写一个flask模块,以后的功能都是在此基础上添加
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/input/')
def input_str():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
然后要建一个文件加必须命名为templates
再这个文件夹里面放入html文件(index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" class="s_ipt" name="wd" id="kw" maxlength="100" autocomplete="off">
</body>
</html>
<body>里面是要现实的功能,这里的<input>是个输入框
<body>里面我们还可以放入别的数据
<body>
<input type="text" class="s_ipt" name="wd" id="kw" maxlength="100" autocomplete="off">
<h1>{{ num }}</h1>
<h2>{{ name }}</h2>
</body>
然后再参数里面设置
return render_template('index1.html',num=1024,name='李四')
这样就可以显示更多的信息了
但是如果信息非常多哪,这中硬编码的方式太麻烦了,我们可以有更好的方法,其中的render_template,我们查看函数说明文档,可以看到它的第二个参数是可变参数,既然可变就可以用解包的形式输入数据
param = dict(num=1024,name='王五')
return render_template('index1.html',**param)
结果是可以完美显示的
当然,既然是字典那是可以在里面嵌套其他的可迭代对象的,
不过想要显示它就要在html添加相应的代码
<body>
<input type="text" class="s_ipt" name="wd" id="kw" maxlength="100" autocomplete="off">
<h1>{{ num }}</h1>
<h2>{{ name }}</h2>
<h3>{{ grade[0] }}</h3>
<h4>{{ grade2['math']}}</h4>
</body>
param = dict(num=1024,name='王五',grade=[89,90,100],grade2={'math':'89','english':'90','chinese':'100'})
return render_template('index1.html',**param)
<body>
<h3>{{ grade[0] }}</h3>
<h4>{{ grade2['math']}}</h4>
</body>
param = dict(num=1024,name='王五',grade=[89,90,100],grade2={'math':'89','english':'90','chinese':'100'})
return render_template('index1.html',**param)
结果如下