Python Flask如何从URL中获取参数?

在Flask中,我如何从URL中提取参数? 我怎样才能使用瓶和python从URL提取命名参数?

当用户访问在我的烧瓶应用程序上运行的这个URL时,我希望Web服务能够处理问号后指定的参数:

http://10.1.1.1:5000/login?username=alex&password=pw1 #I just want to be able to manipulate the parameters @app.route('/login', methods=['GET', 'POST']) def login(): username = request.form['username'] print(username) password = request.form['password'] print(password) 

使用request.args获取查询string的parsing内容:

 from flask import request @app.route(...) def login(): username = request.args.get('username') password = request.args.get('password') 

request.args的URL参数是可用的,它是一个MultiDict ,它有一个get方法,带有默认值( default )和types( type )的可选参数 – 这是一个将input值转换为所需格式的可调用参数。

 from flask import request @app.route('/my-route') def my_route(): page = request.args.get('page', default = 1, type = int) filter = request.args.get('filter', default = '*', type = str) 

上面的代码示例:

 /my-route?page=34 -> page: 34 filter: '*' /my-route -> page: 1 filter: '*' /my-route?page=10&filter=test -> page: 10 filter: 'test' /my-route?page=10&filter=10 -> page: 10 filter: '10' /my-route?page=*&filter=* -> page: 1 filter: '*'