Flask Web Framework – URL Building and HTTP Methods
Till now we have learnt about Flask Introduction, routing, variables name, and URL routing. In this blog we will discuss URL building and HTTP methods.
The url_for() function is very useful for dynamically building a URL for a specific function. The function accepts the name of a function as first argument, each corresponding to the variable part of URL.
The following code demonstrates use of url_for() function.
from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/admin') def hello_admin(): return 'Hello Admin' @app.route('/guest/<guest>
') def hello_guest(guest): return 'Hello %s as Guest' % guest @app.route('/user/<name> ') def hello_user(name): if name == 'admin': return redirect(url_for('hello_admin')) else: return redirect(url_for('hello_guest' , guest = name)) if __name__ == '__main__': app.run(debug = True)
The above code has a function user(name) which accept a value to its argument from the URL.
The User() function checks if an argument received matches ‘admin’ or not. If it marches, the application s redirected to hello_admin() function url_for(), otherwise to the hello_guest() function passing the recieved argument as guest parameter to it.
Save the above code and run from Python shell.
Open the browser and enter URL as –
The application response in browser is –
Enter the following URL in browser is –
The application response now changes to –
Hello brighterbees as Guest
HTTP Protocol is the foundation of data communication in worls wide web. Different methods of data retrieval from specified URL are defined in this protocol.
The following table summarizes different http methods –
Methods and Description
|GET : Sends data in unencrypted form to the server. Most common method.|
|HEAD : Same as GET, but without response body.|
|POST : used to send HTML form data to server. data received by POST method is not cached by server.|
|PUT : Replaces all current representations of the target resource with uploaded content.|
|DELETE : Removes all current representations of the target resource given by a URL.|
By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator.
In order to demonstrate the use of POST method in URL routing, first, let us create an HTML form and use the POST method to send form data to URL.
Save the following code as login.html
App Folder - app.py - login.html
<html> <head> <title>Login</title> </head> <body> <form action = "http://localhost:5000/login" method="POST"> <p>Enter Name : </p> <p><input type = "text" name = "username" /></p> <p><input type = "submit" value= "Submit" /></p> </body> </html>
Now enter the following script in Python shell or CMD
from flask import Flask, redirect, url_for , request app = Flask(__name__) @app.route('/success/<name>') def success(name): return 'Welcome %s' % name @app.route('/login' , methods = ['POST' , 'GET']) def login(): if request.method == 'POST': username = request.form['username'] return redirect(url_for('success' , name = username)) else: username = request.args.get['username'] return redirect(url_for('success' , name = username)) if __name__ == '__main__': app.run(debug = True)
After the development server starts running, open login.html in the browser, enter the name in the text field and click Submit
Form data is posted to the URL in action clause of the form tag.
http://localhost/login is mapped to the login() function. Since the server has received data by POST method, the value of ‘username’ parameter obtained from the form data obtained by –
username = request.form['username']
It is passed to ‘/success’ URL as a variable part. The browser displays welcome message in the window.
Change the Method parameter to “GET” in the login.html and open it again in the browser. The data received on a server is by GET method. the value of ‘username’ parameter is now obtained by –
username = request.args.get['username']
Here, args is a dictionary object containing a list of pairs of form parameter and its corresponding value. the value corresponding to ‘username’ parameter is passed on to ‘/success’ URL as before.
connect with the author on LinkedIn.
visit our website brighterbees for such interesting study stuff and more about flask.
you can also access our blog series on cloud computing.