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.
The Django Web framework for Python is a beginner level PDF e-book tutorial or course with 190 pages. It was added on November 28, 2016 and has been downloaded 25638 times. The file size is 1.26 MB. It was created by Suvash Sedhain.
The JavaScript Front-End Web App Tutorial Part 1 is a beginner level PDF e-book tutorial or course with 48 pages. It was added on February 28, 2016 and has been downloaded 3974 times. The file size is 450.66 KB. It was created by Gerd Wagner.
The The Ultimate Guide to Drupal 8 is a beginner level PDF e-book tutorial or course with 56 pages. It was added on April 5, 2023 and has been downloaded 141 times. The file size is 3.07 MB. It was created by Acquia.
The JavaScript Front-End Web App Tutorial Part 3 is an intermediate level PDF e-book tutorial or course with 24 pages. It was added on February 28, 2016 and has been downloaded 2421 times. The file size is 318.99 KB. It was created by Gerd Wagner.
The JavaScript Front-End Web App Tutorial Part 2 is a beginner level PDF e-book tutorial or course with 35 pages. It was added on February 28, 2016 and has been downloaded 2633 times. The file size is 356.24 KB. It was created by Gerd Wagner .
The Python for android Documentation is a beginner level PDF e-book tutorial or course with 68 pages. It was added on April 11, 2019 and has been downloaded 2924 times. The file size is 284.45 KB. It was created by Alexander Taylor.
The Pyforms (Python) GUI Documentation is a beginner level PDF e-book tutorial or course with 75 pages. It was added on April 22, 2019 and has been downloaded 2021 times. The file size is 353.35 KB. It was created by Ricardo Jorge Vieira Ribeiro.
The JavaScript Front-End Web App Tutorial Part 6 is an advanced level PDF e-book tutorial or course with 28 pages. It was added on February 28, 2016 and has been downloaded 2825 times. The file size is 336.54 KB. It was created by Gerd Wagner.
The Front-End Developer Handbook is a beginner level PDF e-book tutorial or course with 132 pages. It was added on December 15, 2016 and has been downloaded 14495 times. The file size is 1.32 MB. It was created by Cody Lindley.
The Front-end Developer Handbook 2018 is a beginner level PDF e-book tutorial or course with 168 pages. It was added on September 14, 2018 and has been downloaded 20725 times. The file size is 2.39 MB. It was created by Cody Lindley.
The Quick Start Guide Access 2013 is a beginner level PDF e-book tutorial or course with 6 pages. It was added on August 11, 2014 and has been downloaded 1705 times. The file size is 225.96 KB. It was created by MS.
The Access 2013 Create web-based databases is an intermediate level PDF e-book tutorial or course with 10 pages. It was added on August 15, 2014 and has been downloaded 4463 times. The file size is 684.64 KB. It was created by University of Bristol IT Services.
The JavaScript Front-End Web App Tutorial Part 5 is an intermediate level PDF e-book tutorial or course with 19 pages. It was added on February 28, 2016 and has been downloaded 2192 times. The file size is 262.27 KB. It was created by Gerd Wagner.
The Django: Beyond the SQL is a beginner level PDF e-book tutorial or course with 35 pages. It was added on December 2, 2017 and has been downloaded 2023 times. The file size is 182.14 KB. It was created by Jerry Stratton.
The Hands-on Python Tutorial is a beginner level PDF e-book tutorial or course with 207 pages. It was added on September 24, 2020 and has been downloaded 7314 times. The file size is 875.26 KB. It was created by Dr. Andrew N. Harrington.
The A guide to building a video game in Python is an advanced level PDF e-book tutorial or course with 82 pages. It was added on February 2, 2023 and has been downloaded 997 times. The file size is 3.75 MB. It was created by Seth Kenlon and Jess Weichler.
The Python Tutorial is a beginner level PDF e-book tutorial or course with 155 pages. It was added on June 17, 2020 and has been downloaded 175242 times. The file size is 614.5 KB. It was created by Guido van Rossum and the Python development team.
The JavaScript Front-End Web App Tutorial Part 4 is an intermediate level PDF e-book tutorial or course with 37 pages. It was added on February 28, 2016 and has been downloaded 2198 times. The file size is 379.42 KB. It was created by Gerd Wagner.
The Web Services with Examples is a beginner level PDF e-book tutorial or course with 49 pages. It was added on October 20, 2015 and has been downloaded 4293 times. The file size is 1.95 MB. It was created by Hans-Petter Halvorsen.
The Building Web Apps with Go is a beginner level PDF e-book tutorial or course with 39 pages. It was added on January 12, 2017 and has been downloaded 9600 times. The file size is 370.25 KB. It was created by Jeremy Saenz.
The Web application development with Laravel PHP Framework is an intermediate level PDF e-book tutorial or course with 58 pages. It was added on October 3, 2015 and has been downloaded 27990 times. The file size is 1.46 MB. It was created by Jamal Armel.
The Web Programming in Python with Django is a beginner level PDF e-book tutorial or course with 52 pages. It was added on November 28, 2016 and has been downloaded 12529 times. The file size is 410.49 KB. It was created by Steve Levine, Maria Rodriguez, Geoffrey Thomas.
The Your First Node App: Build A Twitter Bot is a beginner level PDF e-book tutorial or course with 18 pages. It was added on October 9, 2017 and has been downloaded 708 times. The file size is 153.7 KB. It was created by Emily Aviva.
The A Short Introduction to Computer Programming Using Python is a beginner level PDF e-book tutorial or course with 34 pages. It was added on March 30, 2020 and has been downloaded 4866 times. The file size is 139.37 KB. It was created by Carsten Fuhs and David Weston.
The Lightning Aura Components Developer Guide is a beginner level PDF e-book tutorial or course with 488 pages. It was added on May 8, 2019 and has been downloaded 1738 times. The file size is 3.74 MB. It was created by salesforcedocs.
The Fundamentals of Python Programming is a beginner level PDF e-book tutorial or course with 669 pages. It was added on January 6, 2019 and has been downloaded 22759 times. The file size is 3.3 MB. It was created by Richard L. Halterman.
The J2EE Web Component Development is a beginner level PDF e-book tutorial or course with 155 pages. It was added on December 8, 2013 and has been downloaded 3201 times. The file size is 945.28 KB. It was created by Chau Keng Fong Adegboyega Ojo.
The CakePHP Cookbook Documentation is a beginner level PDF e-book tutorial or course with 936 pages. It was added on May 13, 2019 and has been downloaded 1310 times. The file size is 2.59 MB. It was created by Cake Software Foundation.
The Getting Started with Dreamweaver CS6 is a beginner level PDF e-book tutorial or course with 32 pages. It was added on July 24, 2014 and has been downloaded 6205 times. The file size is 1.06 MB. It was created by unknown.
The Learning Python Language is a beginner level PDF e-book tutorial or course with 1039 pages. It was added on March 30, 2019 and has been downloaded 13185 times. The file size is 3.74 MB. It was created by Stack Overflow Documentation.