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

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:

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)

This question is related to python web-services flask url-parameters

The answer is


Template Code

<table>
     <tr>
      <th style="min-width: 70px;">Sl No.</th>
      <th style="min-width: 350px;">Description</th>
      <th style="min-width: 100px;">Date</th>
      <th style="min-width: 50px;">Time</th>
      <th style="min-width: 50px;">Status</th>
      <th style="min-width: 50px;">Action</th>
      </tr>
      {% set count = [0] %}
      {% for val in data['todos']%}
      {% if count.append(count.pop() + 1) %}{% endif %}
      <tr>
      <td>{{count[0]}}</td>
      <td>{{val['description']}}</td>
      <td>{{val['date']}}</td>
      <td>{{val['time']}}</td>
      <td>{{val['status']}}</td>
      <td>
        <a class="fa fa-edit" href="#" style=" color: rgb(32, 252, 43);" ></a>
        <a class="fa fa-trash-alt" href="http://localhost:5000/delete?todoid={{val['_id']}}" onmouseout="this.style.color=' rgb(248, 153, 153)'" onmouseover="this.style.color='rgb(241, 74, 74)'" style="padding-left:8%; color: rgb(248, 153, 153);"></a>
      </td>
     </tr>
     {% endfor %}
    </table>

Route code

@app.route('/delete', methods=["GET"])
def deleteTodo():
id = request.args.get('todoid')
print(id)

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

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.


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)


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

  1. On the html template you will declare name attribute for username and password like this:
<form method="POST">
<input type="text" name="user_name"></input>
<input type="text" name="password"></input>
</form>
  1. Then, modify your code like this:
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

The URL parameters are available in request.args, which is an ImmutableMultiDict that has a get method, 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 method for more details.)

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

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

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.

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

#url
http://10.1.1.1:5000/login

HTML snippet:

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

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

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

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 web-services

How do I POST XML data to a webservice with Postman? How to send json data in POST request using C# org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? The request was rejected because no multipart boundary was found in springboot Generating Request/Response XML from a WSDL How to send a POST request using volley with string body? How to send post request to the below post method using postman rest client How to pass a JSON array as a parameter in URL Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

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 url-parameters

What is the difference between URL parameters and query strings? RestTemplate: How to send URL and query parameters together How can I get query parameters from a URL in Vue.js? How can I get the named parameters from a URL using Flask? How to get a URL parameter in Express? PHP check if url parameter exists Pass Hidden parameters using response.sendRedirect() How to convert URL parameters to a JavaScript object? How to replace url parameter with javascript/jquery? Username and password in https url