Introduction
Python is an excellent choice for back-end development due to its readability, versatility, and extensive library support. This tutorial will guide you through building a simple web application using Python and the Flask web framework. We'll cover essential concepts, tools, and best practices to help you kickstart your journey as a Python back-end developer.
Table of Contents
By the end of this tutorial, you'll have a solid understanding of Python back-end development principles and be able to create your own web applications using Flask. Let's dive in!
Flask is a lightweight, easy-to-learn web framework for Python that allows you to build web applications quickly. It's well-suited for small to medium-sized projects and offers great flexibility, making it an excellent choice for beginners.
Before diving into Flask, let's set up your development environment with the necessary tools and software:
Python: Install the latest version of Python from the official website. Make sure to add Python to your system's PATH during installation.
Code Editor or IDE: Choose a code editor or an Integrated Development Environment (IDE) for writing and editing Python code. Some popular options include Visual Studio Code, Sublime Text, and PyCharm.
Virtual Environment: Python virtual environments are used to manage project dependencies and create isolated development environments. Install the virtualenv
package by running pip install virtualenv
in your command-line interface.
Flask: Install the Flask web framework by running pip install flask
in your command-line interface. Note that it's recommended to install Flask within a virtual environment to avoid conflicts with other projects.
Once you have these tools installed, you're ready to start building your Flask web application. In the next tutorial, we'll create a basic Flask web application and explore its structure and components.
Let's start by creating a basic Flask web application. Follow these steps to set up your project structure and create the necessary files:
Create a Project Folder: Create a new folder for your project and name it flask_app
. This folder will hold all the files related to your application.
Initialize a Virtual Environment: Open your command-line interface, navigate to your flask_app
folder, and create a new virtual environment by running virtualenv venv
. Activate the virtual environment using source venv/bin/activate
on macOS/Linux or venv\Scripts\activate
on Windows.
Install Flask: With the virtual environment activated, install Flask by running pip install flask
.
Create Your Main Application File: Inside the flask_app
folder, create a new file named app.py
. This file will hold your main Flask application code.
Write the Flask Application Code: Open app.py
in your code editor and add the following code to create a basic Flask application:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
This code defines a simple Flask application with one route (/
) that returns "Hello, World!" when accessed. The @app.route()
decorator is used to bind the hello_world()
function to the specified route.
flask_app
folder and run python app.py
. Your Flask application should now be running on http://127.0.0.1:5000/
. Open your web browser and visit this address to see your application in action.Congratulations, you've created a basic Flask web application! In the next tutorial, we'll implement user authentication, which is an essential feature for many web applications.
User authentication is a vital component of many web applications, allowing you to restrict access to specific content and functionality. In this tutorial, we'll implement a basic user authentication system using Flask and the Flask-Login extension.
Install Flask-Login: With your virtual environment activated, run pip install Flask-Login
to install the Flask-Login extension.
Create a User Model: Inside your flask_app
folder, create a new file named models.py
. In this file, define a User
class to represent user data:
class User:
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
# Example user data (in a real application, you'd store this in a database)
users = [
User(1, 'user1', 'password1'),
User(2, 'user2', 'password2')
]
In a real-world application, you'd store user data in a database. For simplicity, we're using an in-memory list in this example.
app.py
file to set up and configure Flask-Login:
from flask import Flask, render_template, request, redirect, url_for
from flask_login import LoginManager, login_required, login_user, logout_user
from models import users, User
# Initialize Flask and Flask-Login
app = Flask(__name__)
app.secret_key = 'mysecretkey'
login_manager = LoginManager()
login_manager.init_app(app)
# Load user callback for Flask-Login
@login_manager.user_loader
def load_user(user_id):
return next((user for user in users if user.id == int(user_id)), None)
# Login route
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = next((user for user in users if user.username == username and user.password == password), None)
if user:
login_user(user)
return redirect(url_for('protected_route'))
return render_template('login.html')
# Logout route
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
# Protected route (requires login)
@app.route('/protected')
@login_required
def protected_route():
return 'Welcome to the protected route!'
# Main entry point
if __name__ == '__main__':
app.run()
flask_app
folder, create a new folder named templates
. Inside templates
, create a new file named login.html
with the following content:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="{{ url_for('login') }}">
<label for="username">Username:</label>
<input type="text" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" name="password" required>
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
Now you have a basic user authentication system in place. Users can log in at the /login
route, log out at the /logout
route, and access the protected content at the /protected
route. Test your application by running python app.py
and navigating
In this tutorial, we'll introduce you to working with databases in Flask. We'll use SQLAlchemy, a popular Object Relational Mapper (ORM) for Python, to interact with a SQLite database.
Install Flask-SQLAlchemy and Flask-Migrate: With your virtual environment activated, run pip install Flask-SQLAlchemy Flask-Migrate
to install the necessary extensions.
Configure SQLAlchemy and Migrate: Update your app.py
file to configure and initialize SQLAlchemy and Migrate:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
migrate = Migrate(app, db)
models.py
file to define a User
model that inherits from db.Model
:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
def __repr__(self):
return f'<User {self.username}>'
Initialize Your Database: Run flask db init
in your command-line interface to initialize your database. This will create a new folder named migrations
in your flask_app
folder.
Create Your First Migration: Run flask db migrate
to create your first database migration. This will generate a migration script in the migrations
folder. You can review the script to ensure it accurately reflects the changes you made to your models.
Apply the Migration: Run flask db upgrade
to apply the migration and create the necessary database tables.
Now you have a SQLite database set up and configured with your Flask application. You can use the SQLAlchemy ORM to interact with the database, create new users, and query user data.
In the next tutorial, we'll build a RESTful API with Flask, allowing clients to interact with your application's data and functionality using standardized HTTP methods and endpoints.
A RESTful API (Representational State Transfer) allows clients to interact with your application's data and functionality using standardized HTTP methods and endpoints. In this tutorial, we'll create a simple RESTful API to manage user data.
Install Flask-RESTful: With your virtual environment activated, run pip install Flask-RESTful
to install the Flask-RESTful extension.
Configure Flask-RESTful: Update your app.py
file to configure and initialize Flask-RESTful:
from flask import Flask, request
from flask_restful import Api, Resource
from models import User, db
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
api = Api(app)
app.py
file, create a new UserResource
class that inherits from Resource
. This class will handle HTTP requests related to user data:
class UserResource(Resource):
def get(self, user_id):
user = User.query.get_or_404(user_id)
return {'id': user.id, 'username': user.username}
def put(self, user_id):
user = User.query.get_or_404(user_id)
data = request.get_json()
user.username = data['username']
db.session.commit()
return {'id': user.id, 'username': user.username}
def delete(self, user_id):
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
return {'result': 'User deleted'}
api.add_resource(UserResource, '/api/users/<int:user_id>')
This UserResource
class defines three methods (get
, put
, and delete
) that correspond to the HTTP methods for retrieving, updating, and deleting user data, respectively.
UsersResource
class in your app.py
file:
class UsersResource(Resource):
def post(self):
data = request.get_json()
new_user = User(username=data['username'], password=data['password'])
db.session.add(new_user)
db.session.commit()
return {'id': new_user.id, 'username': new_user.username}
api.add_resource(UsersResource, '/api/users')
Now your Flask application has a RESTful API for managing user data. Clients can create, retrieve, update, and delete users by making HTTP requests to the appropriate endpoints.
In the final tutorial, we'll show you how to deploy your Flask application, making it accessible to users over the internet.
In this tutorial, we'll guide you through deploying your Flask application using Heroku, a popular Platform as a Service (PaaS) provider. Deploying your application makes it accessible to users over the internet.
Install Git: If you haven't already, install Git on your system. You can download Git from the official website.
Create a Heroku Account: Sign up for a free Heroku account at heroku.com.
Install the Heroku CLI: Download and install the Heroku Command Line Interface (CLI) from the official website.
Log in to Heroku: Open your command-line interface and run heroku login
to log in to your Heroku account.
Initialize a Git Repository: Navigate to your flask_app
folder and run git init
to initialize a new Git repository.
Create a .gitignore
File: In your flask_app
folder, create a new file named .gitignore
with the following content:
venv/
*.pyc
*.pyo
*.pyd
__pycache__/
This file tells Git to ignore certain files and folders, such as your virtual environment and compiled Python files.
git add .
git commit -m "Initial commit"
Procfile
: In your flask_app
folder, create a new file named Procfile
(with no file extension) and add the following line:
web: gunicorn app:app
This file tells Heroku how to run your application. In this case, we're using Gunicorn, a production-ready WSGI server for Python applications.
Install Gunicorn: With your virtual environment activated, run pip install gunicorn
to install Gunicorn.
Create a requirements.txt
File: Run pip freeze > requirements.txt
to generate a requirements.txt
file containing all your application's dependencies.
Create a Heroku App: Run heroku create <app_name>
to create a new Heroku app. Replace <app_name>
with a unique name for your application.
Deploy Your Application: Run git push heroku master
to deploy your application to Heroku. This process may take a few minutes.
Open Your Deployed Application: Run heroku open
to open your deployed application in your web browser.
Congratulations! Your Flask application is now deployed and accessible over the internet. You can manage your application, configure add-ons, and monitor performance through the Heroku Dashboard.
In conclusion, this tutorial provided a comprehensive guide to web back-end development using Flask and Python. By following these steps, you've learned to build, deploy, and manage a secure and scalable web application.