Build a URL in Flask
Dynamic Building of the URL for a specific function is done using url_for()
function. The function accepts the name of the function as first argument, and one or more keyword arguments. See this example
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/admin') # decorator for route(argument) function
def hello_admin(): # binding to hello_admin call
return 'Hello Admin'
@app.route('/guest/<guest>')
def hello_guest(guest): # binding to hello_guest call
return 'Hello %s as Guest' % guest
@app.route('/user/<name>')
def hello_user(name):
if name == 'admin': # dynamic binding of URL to function
return redirect(url_for('hello_admin'))
else:
return redirect(url_for('hello_guest', guest=name))
if __name__ == '__main__':
app.run(debug=True)
To test this, save the above code and run through python shell and then open browser and enter the following URL:-
Input: http://localhost:5000/user/admin Output: Hello Admin Input: http://localhost:5000/user/ABC Output: Hello ABC as Guest
The above code has a function named user(name), accepts the value through input URL. It checks that the received argument matches the ‘admin’ argument or not. If it matches, then the function hello_admin() is called else the hello_guest() is called.
HTTP method are provided by Flask
Python Web Framework Flask support various HTTP protocols for data retrieval from the specified URL, these can be defined as:-
Method | Description |
---|---|
GET | This is used to send the data in an without encryption of the form to the server. |
HEAD | provides response body to the form |
POST | Sends the form data to server. Data received by POST method is not cached by server. |
PUT | Replaces current representation of target resource with URL. |
DELETE | Deletes the target resource of a given URL |
Introduction to Web development using Flask
Flask is a lightweight and flexible web framework for Python. It’s designed to make getting started with web development quick and easy, while still being powerful enough to build complex web applications. Let’s understand Flask Python in more Detail