[python] In Flask, What is request.args and how is it used?

I'm new in Flask. I can't understand how request.args is used. I read somewhere that it is used to return values of query string[correct me if I'm wrong]. And how many parameters request.args.get() takes. I know that when I have to store submitted form data, I can use

fname = request.form.get("firstname")

Here, only one parameter is passed.

Consider this code. Pagination has also been done in this code.

@app.route("/")
def home():
    cnx = db_connect()
    cur = cnx.cursor()
    output = []

    page = request.args.get('page', 1)

    try:
        page = int(page)
        skip = (page-1)*4
    except:
        abort(404)

    stmt_select = "select * from posts limit %s, 4;"
    values=[skip]

    cur.execute(stmt_select,values)
    x=cur.fetchall()

    for row in reversed(x):
        data = {
           "uid":row[0],
           "pid":row[1],
           "subject":row[2],
           "post_content":row[3],
           "date":datetime.fromtimestamp(row[4]),
        }
        output.append(data)

    next = page + 1
    previous = page-1
    if previous<1:
    previous=1
    return render_template("home.html", persons=output, next=next, previous=previous)

Here, request.args.get() takes two parameters. Please explain why it takes two parameters and what is the use of it.

This question is related to python python-2.7 flask pagination

The answer is


@martinho as a newbie using Flask and Python myself, I think the previous answers here took for granted that you had a good understanding of the fundamentals. In case you or other viewers don't know the fundamentals, I'll give more context to understand the answer...

... the request.args is bringing a "dictionary" object for you. The "dictionary" object is similar to other collection-type of objects in Python, in that it can store many elements in one single object. Therefore the answer to your question

And how many parameters request.args.get() takes.

It will take only one object, a "dictionary" type of object (as stated in the previous answers). This "dictionary" object, however, can have as many elements as needed... (dictionaries have paired elements called Key, Value).

Other collection-type of objects besides "dictionaries", would be "tuple", and "list"... you can run a google search on those and "data structures" in order to learn other Python fundamentals. This answer is based Python; I don't have an idea if the same applies to other programming languages.


request.args is a MultiDict with the parsed contents of the query string. From the documentation of get method:

get(key, default=None, type=None)

Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible.


It has some interesting behaviour in some cases that is good to be aware of:

from werkzeug.datastructures import MultiDict

d = MultiDict([("ex1", ""), ("ex2", None)])

d.get("ex1", "alternive")
# returns: ''

d.get("ex2", "alternative")
# returns no visible output of any kind
# It is returning literally None, so if you do:
d.get("ex2", "alternative") is None
# it returns: True

d.get("ex3", "alternative")
# returns: 'alternative'

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict

Examples related to flask

Flask at first run: Do not use the development server in a production environment Flask - Calling python function on button OnClick event python-How to set global variables in Flask? In Flask, What is request.args and how is it used? How to print from Flask @app.route to python console What does "app.run(host='0.0.0.0') " mean in Flask Making an asynchronous task in Flask Flask ImportError: No Module Named Flask can you add HTTPS functionality to a python flask web server? How to get http headers in flask?

Examples related to pagination

How to use paginator from material angular? how to implement Pagination in reactJs In Flask, What is request.args and how is it used? Custom pagination view in Laravel 5 Simple pagination in javascript UITableView load more when scrolling to bottom like Facebook application How to use pagination on HTML tables? how to remove pagination in datatable Laravel Pagination links not including other GET parameters API pagination best practices