您现在的位置是:网站首页> 编程资料编程资料

Flask带参URL传值的实现方法_python_

2023-05-25 364人已围观

简介 Flask带参URL传值的实现方法_python_

Flask带参URL传值的方法

在Flask中编写链接URL比较容易,这里并不针对这些讨论,但URL中如果包含可变部分路由以及携带一些参数应该怎么做呢?

我们可以使用Flask模板提供的辅助函数url_for(),这里通过一个完整的小例子来介绍带参URL传值的方法。

定义一个包含动态路由的Flask处理类

from flask import Flask, render_template app = Flask(__name__) @app.route('/') def my(): return render_template('/test.html') @app.route('/test/', methods=['GET']) def test(name): print name return render_template('/test.html') if __name__ == '__main__': app.run(debug=True)

页面

带参URL传值方法点击这里查看

url_for('test',name=1)相当于我们传递的XXX/?name=1,点击这个链接,执行了动态路由test,并将name传入输出,此时显示:http://localhost:5000/test/1

我们看控制台

 

成功将参数打印出来。

还有一种URL传值的格式

假如URL是 http://localhost:5000/tk?xxx=1&xx=1 这种,那我们后台路由如何接收呢?

此时可以使用Flask request方法:request.args.get(),例如,前台请求URL为  http://localhost:5000/tk?p=1&type=1

接收参数的代码

@app.route('/tk', methods=['post','get']) def tk(): p = request.args.get('p') type = request.args.get('type') print(p) print(type) return jsonify({'t': [p, type]})

相比我们更倾向用第一种,无论get或者post都可以使用,也更方便。

Flask传参定义id 及通过传参定义属性名称

字符串不需要通过引号定义,直接连续输入变量转化为字符传

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

-六神源码网