Python 如何使用 Flask 从 URL 获取命名参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24892035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:25:02  来源:igfitidea点击:

How can I get the named parameters from a URL using Flask?

pythonweb-servicesflaskurl-parameters

提问by Alex Stone

When the user accesses this URL running on my flask app, I want the web service to be able to handle the parameters specified after the question mark:

当用户访问在我的 Flask 应用程序上运行的这个 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)

采纳答案by falsetru

Use request.argsto get parsed contents of query string:

使用request.args得到解析查询字符串的内容:

from flask import request

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

回答by qqbenq

The URL parameters are available in request.args, which is an ImmutableMultiDictthat has a getmethod, with optional parameters for default value (default) and type (type) - which is a callable that converts the input value to the desired format. (See the documentation of the methodfor more details.)

URL 参数在 中可用request.args,它是一个具有方法的ImmutableMultiDict,具有get默认值 ( default) 和类型 ( type) 的可选参数- 这是将输入值转换为所需格式的可调用对象。(有关更多详细信息,请参阅该方法文档。)

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)

Examples with the code above:

上面代码的例子:

/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: '*'

回答by Inbar Cheffer

You can also use brackets <> on the URL of the view definition and this input will go into your view function arguments

您还可以在视图定义的 URL 上使用方括号 <>,此输入将进入您的视图函数参数

@app.route('/<name>')
def my_view_func(name):
    return name

回答by Suchita Mukherjee

If you have a single argument passed in the URL you can do it as follows

如果您在 URL 中传递了一个参数,您可以按如下方式进行

from flask import request
#url
http://10.1.1.1:5000/login/alex

from flask import request
@app.route('/login/<username>', methods=['GET'])
def login(username):
    print(username)

In case you have multiple parameters:

如果您有多个参数:

#url
http://10.1.1.1:5000/login?username=alex&password=pw1

from flask import request
@app.route('/login', methods=['GET'])
    def login():
        username = request.args.get('username')
        print(username)
        password= request.args.get('password')
        print(password)

What you were trying to do works in case of POST requests where parameters are passed as form parameters and do not appear in the URL. In case you are actually developing a login API, it is advisable you use POST request rather than GET and expose the data to the user.

在 POST 请求(其中参数作为表单参数传递且未出现在 URL 中)的情况下,您尝试执行的操作有效。如果您实际上正在开发登录 API,建议您使用 POST 请求而不是 GET 并将数据公开给用户。

In case of post request, it would work as follows:

在 post 请求的情况下,它将按如下方式工作:

#url
http://10.1.1.1:5000/login

HTML snippet:

HTML 片段:

<form action="http://10.1.1.1:5000/login" method="POST">
  Username : <input type="text" name="username"><br>
  Password : <input type="password" name="password"><br>
  <input type="submit" value="submit">
</form>

Route:

路线:

from flask import request
@app.route('/login', methods=['POST'])
    def login():
        username = request.form.get('username')
        print(username)
        password= request.form.get('password')
        print(password)

回答by Manish Sharma

url:

网址:

http://0.0.0.0:5000/user/name/

code:

代码:

@app.route('/user/<string:name>/', methods=['GET', 'POST'])
def user_view(name):
    print(name)

(Edit: removed spaces in format string)

(编辑:删除格式字符串中的空格)

回答by Mr.bunty

It's really simple. Let me divide this process into two simple steps.

这真的很简单。让我将这个过程分为两个简单的步骤。

  1. On the html template you will declare name tag for username and password as

    <form method="POST">
    <input type="text" name="user_name"></input>
    <input type="text" name="password"></input>
    </form>
    
  2. Then, modify your code as:

    from flask import request
    
    @app.route('/my-route', methods=['POST']) #you should always parse username and 
    # password in a POST method not GET
    def my_route():
      username = request.form.get("user_name")
      print(username)
      password = request.form.get("password")
      print(password)
    #now manipulate the username and password variables as you wish
    #Tip: define another method instead of methods=['GET','POST'], if you want to  
    # render the same template with a GET request too
    
  1. 在 html 模板上,您将用户名和密码的名称标签声明为

    <form method="POST">
    <input type="text" name="user_name"></input>
    <input type="text" name="password"></input>
    </form>
    
  2. 然后,将您的代码修改为:

    from flask import request
    
    @app.route('/my-route', methods=['POST']) #you should always parse username and 
    # password in a POST method not GET
    def my_route():
      username = request.form.get("user_name")
      print(username)
      password = request.form.get("password")
      print(password)
    #now manipulate the username and password variables as you wish
    #Tip: define another method instead of methods=['GET','POST'], if you want to  
    # render the same template with a GET request too
    

回答by RAJAHMAD MULANI

Use request.args.get(param), for example:

使用request.args.get(param),例如:

http://10.1.1.1:5000/login?username=alex&password=pw1
@app.route('/login', methods=['GET', 'POST'])
def login():
    username = request.args.get('username')
    print(username)
    password = request.args.get('password')
    print(password)

Here is the referenced link to the code.

这是代码的引用链接。