M/s VIKASH TECH - We Write Imaginations to Codes..!!

Flask – Binding URL

First thing that comes to mind when we hear binding is – I guess – BOOKBINDING / PAPER BINDING. Well, this is something similar to that but not exactly. Here, in Flask, binding URL means adding functionalities to some URL.
url_for() is a very useful function used to dynamically build URLs for a specific function. It accepts the first parameter to be the function that needs to be bind, followed by one or more keyword arguments, each corresponding to the variable part of the URL.

Python Code

from flask import Flask, redirect, url_for
app = Flask(__name__)

def hello_admin():
   return 'Hello Admin'

def hello_guest(guest):
   return 'Hello %s as Guest' % guest

def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
      return redirect(url_for('hello_guest',guest = name))

if __name__ == '__main__':
   app.run(debug = True)

In the above example see that the redirect() function is being used to navigate the page to url_for() function page. 
The above script shows a function user(name) that accepts data from a variable to its argument from the URL.
The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is moved to the hello_admin() function using url_for(), otherwise, it is moved to the hello_guest() function passing the received argument as a guest parameter to it.

When you run the code, launch browser, and open URL − http://localhost:5000/user/admin you will get an output –

Hello Admin

Now use this URL to see the change – http://localhost:5000/user/Vikash you will get output as – 

Hello Vikash as Guest 
So now, when we know the few basic things of Flask, it'll become even easy and better to move forward..
Category :


No comments found.

Leave a Reply



Latest Posts

telegram bot

How to send message via Telegram Bot using PHP - Telegram API

Telegram is a great platform for chat and communication purposes. Having a large community and large user base, it is…

SuiteCRM, an open source tool for startups to use from an early stage.

When we talk about businesses in their early stage, it's quite a big deal to choose good management and sales…

How to Implement Google QAuth Authentication | Google Login - PHP MySQL

PHP Google OAuth API allows users to login into a website with their Google credentials. A user with a Google…

How to use Google Two Factor Authentication in your project?

At our end we take security at a priority, implementation of different ways to secure website should be the priority…

%d bloggers like this: