Introduction to Python Flask

In this Python Flask article we want to talk about Introduction to Python Flask, Python Flask is popular micro web framework written in Python. it is used for building web applications and APIs quickly and easily. Flask is lightweight, flexible and easy to use, and this makes it popular choice for developers of all levels of experience. in this article, we want to provide an introduction to Python Flask and explore some of its key features and benefits.

 

 

First of all we need to install Python Flask

 

 

After Flask is installed, we can create new Flask application. create new Python file and import the Flask class

 

 

After that we creates new instance of the Flask class, this creates new Flask application with the name __name__,  __name__ variable is special Python variable that represents the name of the current module. in this case it will be the name of the Python file that you are running.

 

 

Routing in Flask

One of the key features of Flask is its routing system. Routing is the process of matching URL to a specific function in your Flask application. for create a route in Flask, you need to use @app.route decorator. Decorators are a way to modify the behavior of a function without changing its code. in Flask decorators are used to associate URL with a function.

 

This is an example of a simple route that returns Welcome to geekscoders.com when you visit the root URL of your Flask application, in this example @app.route(‘/’) decorator associates the root URL (/) with the hello() function. when you visit the root URL of your Flask application, Flask will call hello() function and return the string Welcome to geekscoders.com.

 

 

Templates in Flask

Flask also supports templates, which are used to render dynamic HTML pages. Templates allow you to separate the presentation logic from the application logic. for using templates in Flask, you need to create templates directory in your Flask application. this directory will contain your HTML templates.

 

This is an example of simple template that uses Jinja2, popular template engine for Flask, in this example, te {{ title }}, {{ heading }} and {% for name in names %} are Jinja2 template tags. they allows you to insert dynamic content into your HTML templates.

 

 

For rendering this template in Flask, you need to use render_template function, in this example, names() function returns names.html template, with title, heading and names variables passed to the template.

 

 

This is the complete code for app.py file

 

 

This is our names.html file

 

 

This is our project structure 

Flask Project Structure
Flask Project Structure

 

 

 

Run the code and go to http://127.0.0.1:5000/names route, this will the results

Introduction to Python Flask
Introduction to Python Flask

 

 

Learn More on Python Flask

Leave a Comment