如何在Flask上获取查询字符串?

问题:如何在Flask上获取查询字符串?

从烧瓶文档中关于如何获取查询字符串的知识并不明显。我是新手,看了看文档,找不到!

所以

@app.route('/')
@app.route('/data')
def data():
    query_string=??????
    return render_template("data.html")

Not obvious from the flask documention on how to get the query string. I am new, looked at the docs, could not find!

So

@app.route('/')
@app.route('/data')
def data():
    query_string=??????
    return render_template("data.html")

回答 0

from flask import request

@app.route('/data')
def data():
    # here we want to get the value of user (i.e. ?user=some-value)
    user = request.args.get('user')
from flask import request

@app.route('/data')
def data():
    # here we want to get the value of user (i.e. ?user=some-value)
    user = request.args.get('user')

回答 1

完整URL可用request.url,而查询字符串可用request.query_string

这是一个例子:

from flask import request

@app.route('/adhoc_test/')
def adhoc_test():

    return request.query_string

要访问在查询字符串中传递的单个已知参数,可以使用request.args.get('param')。据我所知,这是“正确”的方法。

ETA:在继续之前,您应该问自己为什么要查询字符串。我从来没有拉过原始字符串-Flask具有以抽象方式访问它的机制。除非您有令人信服的理由不使用,否则应使用它们。

The full URL is available as request.url, and the query string is available as request.query_string.

Here’s an example:

from flask import request

@app.route('/adhoc_test/')
def adhoc_test():

    return request.query_string

To access an individual known param passed in the query string, you can use request.args.get('param'). This is the “right” way to do it, as far as I know.

ETA: Before you go further, you should ask yourself why you want the query string. I’ve never had to pull in the raw string – Flask has mechanisms for accessing it in an abstracted way. You should use those unless you have a compelling reason not to.


回答 2

Werkzeug / Flask已经为您解析了所有内容。无需使用urlparse再次执行相同的工作:

from flask import request

@app.route('/')
@app.route('/data')
def data():
    query_string = request.query_string  ## There is it
    return render_template("data.html")

有关请求和响应对象的完整文档,请参见Werkzeug:http : //werkzeug.pocoo.org/docs/wrappers/

Werkzeug/Flask as already parsed everything for you. No need to do the same work again with urlparse:

from flask import request

@app.route('/')
@app.route('/data')
def data():
    query_string = request.query_string  ## There is it
    return render_template("data.html")

The full documentation for the request and response objects is in Werkzeug: http://werkzeug.pocoo.org/docs/wrappers/


回答 3

我们可以使用request.query_string做到这一点。

例:

让我们考虑view.py

from my_script import get_url_params

@app.route('/web_url/', methods=('get', 'post'))
def get_url_params_index():
    return Response(get_url_params())

您还可以通过使用Flask蓝图使它更具模块化-http: //flask.pocoo.org/docs/0.10/blueprints/

让我们考虑将名字作为查询字符串/ web_url /?first_name = john的一部分进行传递

## here is my_script.py

## import required flask packages
from flask import request
def get_url_params():
    ## you might further need to format the URL params through escape.    
    firstName = request.args.get('first_name') 
    return firstName

如您所见,这只是一个小例子-您可以获取多个值+为其赋值,然后使用它或将其传递到模板文件中。

We can do this by using request.query_string.

Example:

Lets consider view.py

from my_script import get_url_params

@app.route('/web_url/', methods=('get', 'post'))
def get_url_params_index():
    return Response(get_url_params())

You also make it more modular by using Flask Blueprints – http://flask.pocoo.org/docs/0.10/blueprints/

Lets consider first name is being passed as a part of query string /web_url/?first_name=john

## here is my_script.py

## import required flask packages
from flask import request
def get_url_params():
    ## you might further need to format the URL params through escape.    
    firstName = request.args.get('first_name') 
    return firstName

As you see this is just a small example – you can fetch multiple values + formate those and use it or pass it onto the template file.


回答 4

我来这里是在寻找查询字符串,而不是如何从查询字符串获取值。

request.query_string 返回URL参数作为原始字节字符串(参考文献1)。

使用示例request.query_string

from flask import Flask, request

app = Flask(__name__)

@app.route('/data', methods=['GET'])
def get_query_string():
    return request.query_string

if __name__ == '__main__':
    app.run(debug=True)

输出:

参考文献:

  1. 有关query_string的官方API文档

I came here looking for the query string, not how to get values from the query string.

request.query_string returns the URL parameters as raw byte string (Ref 1).

Example of using request.query_string:

from flask import Flask, request

app = Flask(__name__)

@app.route('/data', methods=['GET'])
def get_query_string():
    return request.query_string

if __name__ == '__main__':
    app.run(debug=True)

Output:

References:

  1. Official API documentation on query_string

回答 5

像这样尝试查询字符串:

from flask import Flask, request

app = Flask(__name__)

@app.route('/parameters', methods=['GET'])
def query_strings():

    args1 = request.args['args1']
    args2 = request.args['args2']
    args3 = request.args['args3']

    return '''<h1>The Query String are...{}:{}:{}</h1>''' .format(args1,args2,args3)


if __name__ == '__main__':

    app.run(debug=True)

输出:

Try like this for query string:

from flask import Flask, request

app = Flask(__name__)

@app.route('/parameters', methods=['GET'])
def query_strings():

    args1 = request.args['args1']
    args2 = request.args['args2']
    args3 = request.args['args3']

    return '''<h1>The Query String are...{}:{}:{}</h1>''' .format(args1,args2,args3)


if __name__ == '__main__':

    app.run(debug=True)

Output:


回答 6

O’Reilly Flask Web开发中所述,可以从烧瓶请求对象中检索每种形式的查询字符串:

O’Reilly Flask Web开发,如Manan Gouhari先前所述,首先,您需要导入请求:

from flask import request

request是Flask公开的对象,它是一个名为(您猜对了)的上下文变量request。顾名思义,它包含客户端包含在HTTP请求中的所有信息。该对象具有许多可以分别检索和调用的属性和方法。

您有很多request属性,其中包含要选择的查询字符串。在这里,我将列出以任何方式包含查询字符串的每个属性,以及O’Reilly对该书的描述。

首先args是“字典,其中所有参数都在URL的查询字符串中传递”。因此,如果要将查询字符串解析为字典,则可以执行以下操作:

from flask import request

@app.route('/'):
    queryStringDict = request.args

(正如其他人指出的,您也可以使用.get('<arg_name>')从字典中获取特定值)

然后,有form属性,它确实包含查询字符串,但它包含在另一个属性的部分包括查询字符串,我将立即上市。不过,首先form是“具有随请求一起提交的所有表单字段的字典”。我这么说是:烧瓶请求对象中还有另一个字典属性可用valuesvalues是“结合了form和中的值的字典args。” 检索将类似于以下内容:

from flask import request

@app.route('/'):
    formFieldsAndQueryStringDict = request.values

(再次,用于.get('<arg_name>')从字典中获取特定项目)

另一个选项是query_string“ URL的查询字符串部分,作为原始二进制值”。例子:

from flask import request

@app.route('/'):
    queryStringRaw = request.query_string

然后,还有一个额外的好处full_path是“ URL的路径和查询字符串部分”。通过ejemplo:

from flask import request

@app.route('/'):
    pathWithQueryString = request.full_path

最后,url“客户端请求的完整URL”(包括查询字符串):

from flask import request

@app.route('/'):
    pathWithQueryString = request.url

快乐黑客:)

Every form of the query string retrievable from flask request object as described in O’Reilly Flask Web Devleopment:

From O’Reilly Flask Web Development, and as stated by Manan Gouhari earlier, first you need to import request:

from flask import request

request is an object exposed by Flask as a context variable named (you guessed it) request. As its name suggests, it contains all the information that the client included in the HTTP request. This object has many attributes and methods that you can retrieve and call, respectively.

You have quite a few request attributes which contain the query string from which to choose. Here I will list every attribute that contains in any way the query string, as well as a description from the O’Reilly book of that attribute.

First there is args which is “a dictionary with all the arguments passed in the query string of the URL.” So if you want the query string parsed into a dictionary, you’d do something like this:

from flask import request

@app.route('/'):
    queryStringDict = request.args

(As others have pointed out, you can also use .get('<arg_name>') to get a specific value from the dictionary)

Then, there is the form attribute, which does not contain the query string, but which is included in part of another attribute that does include the query string which I will list momentarily. First, though, form is “A dictionary with all the form fields submitted with the request.” I say that to say this: there is another dictionary attribute available in the flask request object called values. values is “A dictionary that combines the values in form and args.” Retrieving that would look something like this:

from flask import request

@app.route('/'):
    formFieldsAndQueryStringDict = request.values

(Again, use .get('<arg_name>') to get a specific item out of the dictionary)

Another option is query_string which is “The query string portion of the URL, as a raw binary value.” Example of that:

from flask import request

@app.route('/'):
    queryStringRaw = request.query_string

Then as an added bonus there is full_path which is “The path and query string portions of the URL.” Por ejemplo:

from flask import request

@app.route('/'):
    pathWithQueryString = request.full_path

And finally, url, “The complete URL requested by the client” (which includes the query string):

from flask import request

@app.route('/'):
    pathWithQueryString = request.url

Happy hacking :)


回答 7

可以使用来完成request.args.get()。例如,如果您的查询字符串包含字段date,则可以使用进行访问

date = request.args.get('date')

别忘了request在烧瓶的导入列表中添加“ ”,即

from flask import request

This can be done using request.args.get(). For example if your query string has a field date, it can be accessed using

date = request.args.get('date')

Don’t forget to add “request” to list of imports from flask, i.e.

from flask import request

回答 8

如果请求为GET并且我们传递了一些查询参数,

fro`enter code here`m flask import request
@app.route('/')
@app.route('/data')
def data():
   if request.method == 'GET':
      # Get the parameters by key
      arg1 = request.args.get('arg1')
      arg2 = request.args.get('arg2')
      # Generate the query string
      query_string="?arg1={0}&arg2={1}".format(arg1, arg2)
      return render_template("data.html", query_string=query_string)

If the request if GET and we passed some query parameters then,

fro`enter code here`m flask import request
@app.route('/')
@app.route('/data')
def data():
   if request.method == 'GET':
      # Get the parameters by key
      arg1 = request.args.get('arg1')
      arg2 = request.args.get('arg2')
      # Generate the query string
      query_string="?arg1={0}&arg2={1}".format(arg1, arg2)
      return render_template("data.html", query_string=query_string)