Enable Dark Mode!
what-is-flask-python-and-it-s-key-features.jpg
By: Midilaj VK

What is Flask Python & It's Key Features

Technical

Flask is a popular web framework written in Python, renowned for its straightforwardness, adaptability, and streamlined design. It's the go-to choice for developers who want to build web applications quickly, with minimal configuration and a lot of freedom. Whether you're beginning your journey or aiming to expand your horizons. Learn a lighter framework compared to Django, Flask is a great choice.

This blog will explore the fundamentals of Flask and guide you through creating basic web applications.

What is Flask?

Flask is a lightweight framework for Python. A micro-framework is lightweight, meaning it doesn't come with many built-in features or libraries (like database abstraction layers, form validation, etc.), Flask empowers developers to select their preferred tools and libraries, offering only the core essentials for web development and leaving the rest to your discretion.

Key Features of Flask:

* Lightweight and easy to use

* Built-in development server and debugger

* Restful request dispatching

* Jinja2 templating engine for rendering HTML

* Support for secure cookies (client-side sessions)

* Extensible via Flask extensions

Getting Started with Flask

Let’s walk through the steps to install Flask and create your first basic web application.

1. Setting Up Flask

Before we start building, we need to install Flask. To do this, follow the steps below:

a. Make sure you have Python installed on your system. Flask supports Python 3.x.

b. Open your terminal or command prompt and run the following command to install Flask:

pip install Flask

Once Flask is installed, you’re ready to start building your app.

2. Your First Flask Application

Let’s create a simple web application that displays "Hello, World!" when visited.

a. Create a new file named app.py in your project directory.

b. Add the following code to app.py:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello, World!'
if __name__ == '__main__':
    app.run(debug=True)

Explanation:

* Flask(__name__): This creates a Flask app instance.

* @app.route('/'): This decorator maps the URL '/' (the root URL) to the hello_world function, which returns the string "Hello, World!".

* app.run(debug=True): This runs the application in debug mode, so you can see errors and changes in real-time.

3. Running the Application

In your terminal, navigate to the directory where app.py is located, and run the following command:

python app.py

This will start the Flask development server. Open your web browser and go to http://127.0.0.1:5000/. You should see the message "Hello, World!".

Congratulations! You've just created your first Flask application.

Routing in Flask

Routing refers to the process of mapping URLs to functions. With Flask, you can create multiple routes to handle different parts of your web app. Let’s see how routing works by creating more routes.

Update your app.py as follows:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
    return 'This is the Home Page!'
@app.route('/about')
def about():
    return 'This is the About Page!'
@app.route('/hello/<name>')
def hello_name(name):
    return f'Hello, {name}!'
if __name__ == '__main__':
    app.run(debug=True)

Explanation:

* /: The home page route.

* /about: Another route that returns a simple string.

* /hello/<name>: A dynamic route where <name> is a variable part of the URL. You can replace it with any value (e.g., /hello/John will display "Hello, John!").

This is how Flask makes routing easy and flexible.

Rendering HTML Templates

Flask uses the Jinja2 templating engine, which allows you to write dynamic HTML templates. Let’s create a simple HTML template and render it using Flask.

1. Create a directory named templates in your project folder. Inside this folder, create a file named index.html with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask App</title>
</head>
<body>
    <h1>Welcome to {{ name }}'s Home Page!</h1>
</body>
</html>

2. Now, update app.py to render this template:

from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
    return render_template('index.html', name='John')
if __name__ == '__main__':
    app.run(debug=True)

Explanation:

* render_template('index.html', name='John'): This tells Flask to look for index.html in the templates directory and pass the variable name to it.

* Inside index.html, {{ name }} is replaced by the value of the name variable (John in this case).

When you run this and visit http://127.0.0.1:5000/, you'll see a web page with the title "Flask App" and the text "Welcome to John’s Home Page!"

Handling Forms in Flask

One of the core functionalities of web applications is handling user input through forms. Let’s create a simple form where users can submit their names, and the app will display a greeting message.

1. First, create a new file named form.html inside the templates folder with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Form</title>
</head>
<body>
    <form action="/greet" method="POST">
        <label for="name">Enter your name:</label>
        <input type="text" name="name" id="name">
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Now, update app.py to handle the form:

from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
    return render_template('form.html')
@app.route('/greet', methods=['POST'])
def greet():
    name = request.form['name']
    return f'Hello, {name}!'
if __name__ == '__main__':
    app.run(debug=True)

Explanation:

* request.form['name']: This grabs the user input from the form (the value they entered into the name field).

* methods=['POST']: This allows the /greet route to handle POST requests (used for submitting form data).

Run the app and submit the form, and you'll see the greeting message displayed with the name you entered.

Conclusion

Flask is an excellent framework for building lightweight and simple web applications. In this blog, we covered the basics:

* Setting up Flask

* Creating routes

* Rendering HTML templates

* Handling forms

From here, you can start exploring Flask’s advanced features, such as integrating databases, working with Flask extensions, or deploying your application to the web.

To read more about How to Configure Python & SQL Constraints in Odoo 18, refer to our blog How to Configure Python & SQL Constraints in Odoo 18.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment

 


whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message