By ATS Staff on September 1st, 2023
Python ProgrammingFlask is a lightweight web framework for Python, celebrated for its simplicity, flexibility, and ease of use. It allows developers to build web applications quickly with minimal boilerplate code, making it one of the most popular choices for both beginners and experienced developers.
Flask is a micro-framework for Python, meaning it provides the essential tools needed to build web applications but leaves room for customization. Unlike other web frameworks like Django, which are feature-rich and come with built-in tools for everything from authentication to form validation, Flask offers a more minimalistic approach, letting developers pick and choose which components they want to add.
Flask was created by Armin Ronacher as part of the Pallets Project, and its simplicity stems from the fact that it’s built on two main dependencies:
Here’s a simple example to demonstrate how to create a basic web application using Flask:
pip install Flask
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' if __name__ == '__main__': app.run(debug=True)
app.py
) and run it:python app.py
Visit http://127.0.0.1:5000/
in your browser, and you should see the message "Hello, World!"
In Flask, routing refers to mapping a URL to a specific function in your application. The @app.route()
decorator defines a route and binds it to a view function.
Example:
@app.route('/about') def about(): return "This is the About page"
Here, visiting /about
in the browser would call the about()
function and return the string "This is the About page."
Templates in Flask allow you to generate HTML dynamically by embedding Python code within HTML files. Flask uses the Jinja2 templating engine for this purpose.
Example of using a template:
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html', title="Home") if __name__ == '__main__': app.run(debug=True)
In the templates/index.html
file:
<!DOCTYPE html> <html> <head> <title>{{ title }}</title> </head> <body> <h1>Welcome to {{ title }} page!</h1> </body> </html>
The {% %}
and {{ }}
syntax allows you to write Python code within HTML.
Flask makes it easy to handle form submissions and process data. You can use the request
object to access form data sent via POST requests.
from flask import Flask, request app = Flask(__name__) @app.route('/submit', methods=['POST']) def submit(): username = request.form.get('username') return f'Hello, {username}!'
In the HTML form:
<form action="/submit" method="POST"> <input type="text" name="username"> <input type="submit" value="Submit"> </form>
Flask does not come with a built-in ORM (Object Relational Mapper) like Django, but you can integrate it with popular ORMs like SQLAlchemy.
To install SQLAlchemy:
pip install Flask-SQLAlchemy
Here’s an example of how to connect Flask to a SQLite database using SQLAlchemy:
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) def __repr__(self): return f'<User {self.username}>'
Flask has a large ecosystem of extensions that add functionality. Some popular Flask extensions include:
Flask is a powerful, flexible, and minimalist web framework that provides developers with the essential tools for building web applications. Its simplicity, combined with the ability to extend it with third-party libraries, makes it ideal for projects ranging from simple prototypes to complex, scalable applications. Whether you are a beginner just starting with web development or an experienced developer looking for a framework that gives you more control, Flask is an excellent choice.