Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain values of parameters of get request in flask?

The answer that I found on the web is to use request.args.get. However, I cannot manage it to work. I have the following simple example:

from flask import Flask app = Flask(__name__)  @app.route("/hello") def hello():     print request.args['x']     return "Hello World!"  if __name__ == "__main__":     app.run() 

I go to the 127.0.0.1:5000/hello?x=2 in my browser and as a result I get:

Internal Server Error  The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application. 

What am I doing wrong?

like image 727
Roman Avatar asked Mar 13 '14 15:03

Roman


People also ask

How do I get parameters in GET request?

GET parameters (also called URL parameters or query strings) are used when a client, such as a browser, requests a particular resource from a web server using the HTTP protocol. These parameters are usually name-value pairs, separated by an equals sign = . They can be used for a variety of things, as explained below.

How do I find request parameters in Flask?

In the first one we would use request. args. get('<argument name>') where request is the instance of the class request imported from Flask. Args is the module under which the module GET is present which will enable the retrieve of the parameters.

Can a get request have query parameters?

You may use the queryParam() method not just once, but as many times as the number of query parameters in your GET request.

How do you get data from a Flask request body?

Use request. form to get data when submitting a form with the POST method. Use request. args to get data passed in the query string of the URL, like when submitting a form with the GET method.


2 Answers

The simple answer is you have not imported the request global object from the flask package.

from flask import Flask, request 

This is easy to determine yourself by running the development server in debug mode by doing

app.run(debug=True) 

This will give you a stacktrace including:

print request.args['x'] NameError: global name 'request' is not defined 
like image 186
sberry Avatar answered Oct 06 '22 00:10

sberry


http://localhost:5000/api/iterators/opel/next?n=5

For something like the case before

from flask import Flask, request n = request.args.get("n") 

Can do the trick

like image 43
Joe9008 Avatar answered Oct 06 '22 01:10

Joe9008