Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

python - In Flask, what is "request.args" and how is it used?

As a Flask beginner, 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, whereas the code below takes two parameters.

@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)

Please explain why it takes two parameters, and then what its use is.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the flask.Request.args documents.

flask.Request.args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

So the args.get() is method get() for MultiDict, whose prototype is as follows:

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

In newer version of flask (v1.0.x and v1.1.x), flask.Request.args is an ImmutableMultiDict(an immutable MultiDict), so the prototype and specific method above are still valid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...