4 May 2023
This article is brought to you by JBI Training, the UK's leading technology training provider. Learn more about JBI's Python training courses including Python (Advanced), Python Machine Learning, and Python for Financial Traders
Flask is a popular web framework for Python that allows developers to quickly and easily build web applications. In this guide, we'll provide an overview of Flask and its benefits, and then walk through the process of building a simple web application using Flask.
Explanation of Flask
Flask is a micro web framework that allows developers to quickly build web applications using Python. It is lightweight and flexible, making it a popular choice for building small to medium-sized web applications. Flask provides a simple and intuitive interface for handling requests and responses, making it easy to get started with web development in Python.
Benefits of Using Flask for Web Development
Overview of the Guide
In this guide, we'll walk through the process of building a simple web application using Flask. We'll start by setting up a virtual environment to ensure our dependencies are isolated from other Python projects on our system. Then, we'll create a basic Flask application and run it locally. Finally, we'll deploy the application to a cloud platform so it can be accessed from anywhere.
Flask is a powerful and flexible web framework for Python, but in order to build and test applications, we need to create a virtual environment to ensure that our dependencies are isolated from other Python projects on our system. In this section, we'll explain what a virtual environment is, how to create one, and how to activate and deactivate it.
Explanation of Virtual Environments
A virtual environment is a self-contained directory that contains a Python interpreter and all of the packages and modules required for a specific project. By creating a virtual environment, we can ensure that any packages installed or upgraded for one project do not affect other projects on the same system. This is particularly important when working on multiple projects with different requirements or when deploying code to a production environment.
Steps for Creating a Virtual Environment
Open your terminal or command prompt.
Navigate to the directory where you want to create your virtual environment.
Type the following command to create a new virtual environment:
python -m venv <env_name>
Note: Replace <env_name>
with the name you want to give your virtual environment.
After running this command, a new directory with the name you chose will be created in your current directory.
Now we need to activate the virtual environment so we can use it.
Activating and Deactivating the Virtual Environment
To activate the virtual environment we just created, we need to run the activate script. The location of the activate script is different depending on your operating system.
Open your terminal or command prompt.
Navigate to the directory where your virtual environment was created.
Navigate to the Scripts
directory within the virtual environment directory.
Run the following command:
activate
This will activate your virtual environment.
Open your terminal or command prompt.
Navigate to the directory where your virtual environment was created.
Navigate to the bin
directory within the virtual environment directory.
Run the following command:
source activate
This will activate your virtual environment.
To deactivate the virtual environment, simply type deactivate
in the command prompt or terminal.
Explanation of Flask Installation
Before we can start building our web application using Flask, we need to install the framework. Flask can be easily installed using pip, a package manager for Python. Here's how to install Flask on your system:
Installing Flask via pip
To install Flask via pip, open up your terminal or command prompt and type the following command:
pip install flask
This will download and install Flask and its dependencies on your system. Depending on your system and internet connection speed, this may take a few minutes to complete.
Verifying Flask Installation
To verify that Flask has been installed correctly, you can create a new Python file and try importing Flask. Here's an example:
# Import the Flask class from the flask module from flask import Flask # Create a new Flask application instance app = Flask(__name__) # Define a route @app.route('/') def hello_world(): return 'Hello, World!'
Save this file as app.py
, and then open up your terminal or command prompt and navigate to the directory where the file is located. Once you're there, run the following command:
python app.py
This will start the Flask development server and make your application available at https://localhost:5000/
.
If everything was installed correctly, you should see the message "Hello, World!" displayed in your web browser when you navigate to https://localhost:5000/
.
Now that we have Flask installed, we can create our Flask app. Here's how to get started:
Creating the Project Directory
First, let's create a new directory for our project. Open up your terminal or command prompt and navigate to the directory where you want to create your project directory. Then, run the following command:
mkdir myapp
This will create a new directory called myapp
for our project.
Creating the Flask App File
Now that we have our project directory, let's create a new Python file for our Flask app. Inside the myapp
directory, create a new file called app.py
.
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello, World!'
This code creates a new Flask app instance and defines a single route that returns the string "Hello, World!".
Adding Routes and Views to the Flask App
Now that we have our basic Flask app set up, let's add some routes and views to it. For example, let's add a new route that displays a list of items.
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello, World!' @app.route('/items') def list_items(): items = ['Item 1', 'Item 2', 'Item 3'] return '<br>'.join(items)
This code adds a new route to our app that displays a list of items. When you navigate to https://localhost:5000/items
, you should see a list of items displayed in your web browser.
Running the Flask App
Now that we have our Flask app set up and some routes and views defined, let's run the app. To do this, open up your terminal or command prompt and navigate to the myapp
directory. Then, run the following command:
export FLASK_APP=app.py flask run
This will start the Flask development server and make your application available at https://localhost:5000/
.
If everything was set up correctly, you should see the message "Hello, World!" displayed when you navigate to https://localhost:5000/
, and a list of items displayed when you navigate to https://localhost:5000/items
.
When building web applications, it's important to separate the application logic from the presentation layer. Flask makes this easy by supporting the use of templates. Templates allow you to separate the structure of your HTML pages from the content that is dynamically generated by your application.
Flask uses the Jinja2 templating engine to render templates. Jinja2 is a fast and powerful template engine that allows for dynamic templates and includes features such as template inheritance, filters, and macros.
To create a template in Flask, you need to create an HTML file with placeholders for the dynamic content. These placeholders are typically written in double curly braces {{ }}
.
Here's an example of a basic template in Flask:
<!DOCTYPE html> <html> <head> <title>{{ title }}</title> </head> <body> <h1>{{ heading }}</h1> <p>{{ content }}</p> </body> </html>
In this example, the placeholders {{ title }}
, {{ heading }}
, and {{ content }}
will be dynamically replaced with the values passed to the template from the Flask application.
You can also create a base template that contains the common structure and layout for your pages, and then extend this base template in your child templates. This allows you to maintain a consistent look and feel across all of your pages while still allowing for dynamic content.
Here's an example of a base template in Flask:
<!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <header> <h1>{% block heading %}{% endblock %}</h1> </header> <main> {% block content %}{% endblock %} </main> <footer> <p>Copyright © {{ year }} {{ author }}</p> </footer> </body> </html>
In this example, the {% block %}
statements define the areas of the template that can be overridden by child templates. The child templates can override these blocks by using the {% extends %}
and {% block %}
statements.
Here's an example of a child template that extends the base template:
{% extends "base.html" %} {% block title %}Home{% endblock %} {% block heading %}Welcome to my website!{% endblock %} {% block content %} <p>Hello, world!</p> {% endblock %}
In this example, the {% extends %}
statement tells Flask to use the base.html
template as the base for this template. The {% block %}
statements then override the blocks defined in the base template.
By using templates in your Flask application, you can separate the presentation layer from the application logic, making it easier to maintain and update your application.
Flask provides several database options, including PostgreSQL, MySQL, and SQLite. For this guide, we will be using SQLite, which is a simple and lightweight database that doesn't require a separate server to run.
To get started, we need to install the SQLite database library and the Flask-SQLAlchemy extension. We can do this by running the following command in our virtual environment:
pip install flask-sqlalchemy
After the installation is complete, we can create a new file called models.py
in our project directory. This file will contain the database schema for our application.
Here is an example of a basic database schema for a blog:
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(50), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) password = db.Column(db.String(60), nullable=False) posts = db.relationship('Post', backref='author', lazy=True) def __repr__(self): return f"User('{self.username}', '{self.email}')" class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) content = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) def __repr__(self): return f"Post('{self.title}', '{self.date_posted}')"
In this example, we have defined two models: User
and Post
. Each model is represented by a class that inherits from db.Model
. The db.Column
method is used to define the columns of each table, and the relationships between the tables are defined using the db.relationship
method.
To use this database schema in our Flask app, we need to initialize the db
object in our app.py
file and add the database URI. Here is an example:
from flask import Flask from models import db app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db.init_app(app) from routes import * if __name__ == '__main__': app.run(debug=True)
In this example, we import the db
object from our models.py
file and initialize it with our app
object. We also set the SQLALCHEMY_DATABASE_URI
configuration variable to specify the path to our SQLite database file. Finally, we import our routes and start the Flask app.
To create the database tables, we can use the following command in the Flask shell:
>>> from models import db >>> db.create_all()
This command will create all the tables defined in our models.py
file.
We can now interact with the database in our Flask app using the db
object. For example, to add a new user to the database, we can do the following:
from models import db, User user = User(username='john', email='[email protected]', password='password') db.session.add(user) db.session.commit()
In this example, we create a new User
object and add it to the session using the db.session.add()
method. We then commit the changes to the database using the db.session.commit()
method.
o use this database schema in our Flask app, we need to initialize the db
object in our app.py
file and add the database URI. Here is an example:
from flask import Flask from models import db app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db.init_app(app) from routes import * if __name__ == '__main__': app.run(debug=True)
In this example, we import the db
object from our models.py
file and initialize it with our app
object. We also set the SQLALCHEMY_DATABASE_URI
configuration variable to specify the path to our SQLite database file. Finally, we import our routes and start the Flask app.
To create the database tables, we can use the following command in the Flask shell:
>>> from models import db >>> db.create_all()
This command will create all the tables defined in our models.py
file.
We can now interact with the database in our Flask app using the db
object. For example, to add a new user to the database, we can do the following:
from models import db, User user = User(username='john', email='[email protected]', password='password') db.session.add(user) db.session.commit()
In this example, we create a new User
object and add it to the session using the db.session.add()
method. We then commit the changes to the database using the db.session.commit()
method.
By adding a database to our Flask app, we can create more complex and
dynamic web applications that store and retrieve data as needed. Let's now move on to creating a database schema.
In SQLAlchemy, we define our database schema using Python classes that inherit from the db.Model
class. Each class represents a database table and its attributes represent the table columns.
Here's an example of a simple database schema for a blog application:
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100)) content = db.Column(db.Text) pub_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
In this example, we define a Post
table that has id
, title
, content
, and pub_date
columns. We also specify that the id
column is the primary key and auto-incrementing.
We can now use this schema to create our database tables by running the following commands in the terminal:
flask db init flask db migrate flask db upgrade
The flask db init
command initializes the database migrations directory, the flask db migrate
command generates a migration script based on our schema changes, and the flask db upgrade
command applies the migration script to our database.
With our database schema created and our database set up, we can now start interacting with the database in our Flask app. We can use SQLAlchemy's built-in methods to create, read, update, and delete records in our database.
Here's an example of how we can create a new post in our Post table:
from app import db, Post new_post = Post(title='My New Post', content='This is my new post content') db.session.add(new_post) db.session.commit()
In this example, we first import the db
object and the Post
model from our app
package. Then, we create a new Post
object with a title and content. We add the new post to the database session with db.session.add(new_post)
and then commit the session to save the changes with db.session.commit()
.
We can also retrieve posts from the database using queries. Here's an example of how we can retrieve all posts from the Post
table:
from app import db, Post posts = Post.query.all()
This query returns a list of all Post
objects in the database.
Overall, adding a database to our Flask app opens up a world of possibilities for building dynamic, data-driven web applications. With Flask's powerful built-in database tools and the flexibility to work with any database system, we can easily create and interact with databases to store and retrieve data for our applications.
Authentication is an important aspect of any web application, and Flask provides several extensions to make it easier to implement. In this section, we will add authentication to our Flask app using Flask-Login.
Explanation of Authentication in Flask: Authentication is the process of verifying the identity of a user. In web applications, authentication is usually done by asking the user to provide their username and password. Once the user's identity is verified, they are granted access to the application's protected resources.
Flask-Login is a Flask extension that provides user session management, user authentication, and authorization features. It makes it easy to implement user authentication in Flask applications.
Installing and Configuring Flask-Login: To install Flask-Login, we can use pip:
pip install Flask-Login
Once we have installed Flask-Login, we can configure it in our Flask app by creating a login manager instance:
from flask_login import LoginManager app = Flask(__name__) login_manager = LoginManager() login_manager.init_app(app)
Creating a User Model: Before we can implement user authentication, we need to create a user model. The user model will represent the user in our application and will be used to store user information such as their username and password.
Here's an example of a User model:
from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) def __repr__(self): return '<User {}>'.format(self.username) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password)
Implementing User Registration and Login: Now that we have a User model, we can implement user registration and login. Flask-Login provides several helper functions to make it easier to implement user authentication.
Here's an example of how we can implement user registration:
from flask import render_template, flash, redirect, url_for from flask_login import current_user, login_user from app.forms import LoginForm, RegistrationForm from app.models import User @app.route('/register', methods=['GET', 'POST']) def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
Here's an example of how we can implement user login:
@app.route('/login', methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) return redirect(url_for('index'))
Adding authentication to our Flask
from flask import Flask, render_template, request, redirect, url_for from flask_login import LoginManager, login_user, logout_user, login_required, UserMixin app = Flask(__name__) app.secret_key = 'secret_key' login_manager = LoginManager() login_manager.init_app(app) # our user model class User(UserMixin): def __init__(self, id): self.id = id # some fake users users = {'[email protected]': {'password': 'secret'}, '[email protected]': {'password': 'secret'}} @login_manager.user_loader def load_user(user_id): return User(user_id) @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') email = request.form['email'] if email not in users: return redirect(url_for('login')) user = User(email) login_user(user) return redirect(url_for('index')) @app.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('login')) @app.route('/') @login_required def index(): return render_template('index.html')
In this example, we create a User
model which inherits from UserMixin
provided by Flask-Login. We also define a login_manager
and set it up in our app
instance.
Then, we define some fake users and a load_user
function which returns the user with the given id.
The /login
route handles both GET and POST requests. If the request is a GET request, we simply render the login template. If the request is a POST request, we get the email from the form and check if it exists in our fake users. If it does, we create a new User
instance with the given email and login the user using the login_user
function provided by Flask-Login.
The /logout
route logs out the user and redirects them to the login page.
Finally, the /
route is the main page of our app and can only be accessed by logged-in users. If a user is not logged in and tries to access this page, they will be redirected to the login page.
Forms are a critical part of most web applications, and Flask makes it easy to add them to your application. In this section, we'll cover how to add forms to your Flask application using the Flask-WTF extension.
A form in Flask is an HTML form that sends data to the server. The server then processes the data and returns a response. Forms can be used to collect user data, such as login credentials, contact information, or search queries.
Flask-WTF is an extension that provides integration between Flask and the popular WTForms library. WTForms is a flexible form library for Python that allows developers to create forms with validation and rendering logic. To install Flask-WTF, you can use pip, the Python package manager:
pip install flask-wtf
Once you have installed Flask-WTF, you need to import it into your Flask application and configure it with a secret key. The secret key is used to protect against CSRF (cross-site request forgery) attacks. Here's an example of how to configure Flask-WTF:
from flask import Flask from flask_wtf import CSRFProtect app = Flask(__name__) app.config['SECRET_KEY'] = 'secret key' csrf = CSRFProtect(app)
In Flask, forms are created using the WTForms library. To create a form, you need to define a Python class that inherits from the flask_wtf.FlaskForm
class. This class defines the fields of the form and any validation logic.
Here's an example of how to create a simple form class that includes two fields: name
and email
:
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired, Email class MyForm(FlaskForm): name = StringField('Name', validators=[DataRequired()]) email = StringField('Email', validators=[DataRequired(), Email()]) submit = SubmitField('Submit')
In this example, we create a simple form with two fields: name
and email
. We also create a submit
button. The validators
argument is used to specify the validation logic for each field.
To render a form in a Flask template, you need to use the form
object that is passed to the template. The form
object is created by creating an instance of the form class.
Here's an example of how to render the MyForm
class in a template called form.html
:
<form method="POST" action="{{ url_for('index') }}"> {{ form.hidden_tag() }} {{ form.name.label }} {{ form.name }} {{ form.email.label }} {{ form.email }} {{ form.submit }} </form>
In this example, we define a form with the method
and action
attributes. The hidden_tag()
method is used to include a CSRF token in the form. We then render each field of the form using the label
and data
attributes of the form.
To process form data in Flask, you need to define a route that handles the form submission. In the route function, you can access the form data using the request.form
object.
Here's an example of how we can handle form submissions:
@app.route('/', methods=['GET', 'POST']) def index(): form = MyForm() if form.validate_on_submit(): name = form.name.data
Here's an example of how we can handle form submissions:
@app.route('/submit_form', methods=['POST']) def submit_form(): name = request.form['name'] email = request.form['email'] # do something with the form data return redirect(url_for('index'))
In this example, we define a route for the form submission URL, which is accessed using the HTTP POST method. In the function, we retrieve the form data using the request.form
object and access the values of the form fields by their names. We can then perform any necessary processing on the data and return a redirect response to another page.
By following these steps, you can easily create forms in your Flask app and process user input. This can be useful for a wide range of applications, such as user registration, contact forms, and search filters, among others.
In this guide, we've covered the basic steps to create a simple web application using Flask, a popular web framework for Python. We started by setting up our development environment and installing Flask and other required packages. Then, we created a Flask app and added routes and views to handle HTTP requests and responses. We also learned how to create templates using Jinja2, a powerful and flexible template engine that allows us to create dynamic and reusable HTML pages.
Next, we added a database to our Flask app using SQLAlchemy, a Python SQL toolkit and ORM that provides a high-level interface to interact with relational databases. We created a Post model and a User model, and defined the relationships between them. We also implemented basic CRUD (create, read, update, delete) operations for our models using SQLAlchemy's API.
After that, we added authentication to our Flask app using Flask-Login, a user session management library for Flask. We created a User model that stores user credentials and used Flask-Login's API to handle user registration, login, and logout. We also added some basic security features, such as password hashing and login/logout redirects.
Finally, we added forms to our Flask app using Flask-WTF, a form handling library for Flask. We created a simple form class and rendered it in a template using Jinja2. We also implemented a form submission route that handles POST requests and processes the form data.
Of course, this guide only scratches the surface of what you can do with Flask. There are many more features and extensions that you can use to create more complex and powerful web applications. We encourage you to explore the Flask documentation and the Flask community to learn more about this amazing framework.
Further resources for learning Flask:
We hope you enjoyed this guide and found it useful for getting started with Flask. Good luck with your web development projects!
To further your training we'd recommend.
Python: This course covers the basics of the Python programming language and is a great starting point for beginners.
Python Machine Learning This course covers the basics of machine learning using Python, including supervised and unsupervised learning, and how to use Python libraries like scikit-learn and TensorFlow.
Python for Financial Traders: This course is specifically designed for traders and covers how to use Python for financial analysis, backtesting, and trading strategies.
Python & NLP: This course covers natural language processing techniques using Python, including text classification, sentiment analysis, and named entity recognition.
Python (Advanced): This course covers advanced Python topics such as decorators, generators, and meta-classes, and is designed for experienced Python developers.
CONTACT
+44 (0)20 8446 7555
Copyright © 2024 JBI Training. All Rights Reserved.
JB International Training Ltd - Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS
Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us