COMPUTER-PDF.COM

Getting Started with Python Back-End Development: Your First Web App

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!

Introduction to Flask and Setting Up Your Environment

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:

  1. Python: Install the latest version of Python from the official website. Make sure to add Python to your system's PATH during installation.

  2. 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.

  3. 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.

  4. 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.

Creating a Basic Flask Web Application

Let's start by creating a basic Flask web application. Follow these steps to set up your project structure and create the necessary files:

  1. 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.

  2. 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.

  3. Install Flask: With the virtual environment activated, install Flask by running pip install flask.

  4. 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.

  5. 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.

  6. Run the Flask Application: In your command-line interface, navigate to the 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.

Implementing User Authentication

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.

  1. Install Flask-Login: With your virtual environment activated, run pip install Flask-Login to install the Flask-Login extension.

  2. 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.

  3. Configure Flask-Login: Update your 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()
    
  4. Create Login Template: Inside your 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

Working with Databases in Flask

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.

  1. Install Flask-SQLAlchemy and Flask-Migrate: With your virtual environment activated, run pip install Flask-SQLAlchemy Flask-Migrate to install the necessary extensions.

  2. 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)
    
  3. Create a User Model: Update your 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}>'
    
  4. 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.

  5. 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.

  6. 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.

Building a RESTful API with Flask

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.

  1. Install Flask-RESTful: With your virtual environment activated, run pip install Flask-RESTful to install the Flask-RESTful extension.

  2. 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)
    
  3. Create a User Resource: In your 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.

  4. Create a Users Resource: To handle creating new users, create a 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.

Deploying Your Flask Application

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.

  1. Install Git: If you haven't already, install Git on your system. You can download Git from the official website.

  2. Create a Heroku Account: Sign up for a free Heroku account at heroku.com.

  3. Install the Heroku CLI: Download and install the Heroku Command Line Interface (CLI) from the official website.

  4. Log in to Heroku: Open your command-line interface and run heroku login to log in to your Heroku account.

  5. Initialize a Git Repository: Navigate to your flask_app folder and run git init to initialize a new Git repository.

  6. 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.

  7. Commit Your Application: Run the following commands to commit your application to the Git repository:
    git add .
    git commit -m "Initial commit"
    
  8. Create a 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.

  9. Install Gunicorn: With your virtual environment activated, run pip install gunicorn to install Gunicorn.

  10. Create a requirements.txt File: Run pip freeze > requirements.txt to generate a requirements.txt file containing all your application's dependencies.

  11. 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.

  12. Deploy Your Application: Run git push heroku master to deploy your application to Heroku. This process may take a few minutes.

  13. 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.

Related tutorials

ASP.NET Basics: Crafting Your First Web App

Web API Development with Python: A Practical Guide

Mobile-First Development: Optimization & Best Practices

Creating Your First VPN: Step-by-Step Guide: Tutorial for Beginners

What is Flask? Get Started with Building Secure Web Apps with Python

Getting Started with Python Back-End Development: Your First Web App online learning

Django Web framework for Python

Download free Django Web framework for Python course tutorial and training, a PDF book made by Suvash Sedhain.


JavaScript Front-End Web App Tutorial Part 1

Learn how to build a front-end web application with minimal effort, using plain JavaScript and the LocalStorage API, PDF file by Gerd Wagner.


The Ultimate Guide to Drupal 8

Master Drupal 8 with our comprehensive PDF tutorial, The Ultimate Guide to Drupal 8. Unlock powerful features and build outstanding websites. Download now!


JavaScript Front-End Web App Tutorial Part 3

Learn how to build a front-end web application with enumeration attributes, using plain JavaScript, PDF file by Gerd Wagner.


JavaScript Front-End Web App Tutorial Part 2

Learn how to build a front-end web application with responsive constraint validation using plain JavaScript, PDF file by Gerd Wagner .


Python for android Documentation

Download free ebook Python for android Documentation, PDF course tutorial by Alexander Taylor.


Pyforms (Python) GUI Documentation

Download free ebook Pyforms (Python) GUI Documentation, PDF course tutorials by Ricardo Jorge Vieira Ribeiro.


JavaScript Front-End Web App Tutorial Part 6

An advanced tutorial about developing front-end web applications with class hierarchies, using plain JavaScript, PDF file by Gerd Wagner.


Front-End Developer Handbook

Learn front-end development from scratch with the 'Front-End Developer Handbook' PDF tutorial by Cody Lindley.


Front-end Developer Handbook 2018

Download Front-end Developer Handbook 2018 ebook, client-side development with client-side development is the practice of producing HTML, CSS and JavaScript. free PDF on 168 pages.


Quick Start Guide Access 2013

Microsoft Access 2013 looks different from previous versions, so we created this guide to help you minimize the learning curve. PDF file.


Access 2013 Create web-based databases

Download free Access 2013 Create web-based databases course material, tutorial training, a PDF file by University of Bristol IT Services.


JavaScript Front-End Web App Tutorial Part 5

Learn how to manage bidirectional associations between object types, such as between books and their authors, and authors and their books, PDF file by Gerd Wagner.


Django: Beyond the SQL

Download tutorial Django Beyond the SQL application framework for Python and web applications, free PDF course ebook.


Hands-on Python Tutorial

Learn Python programming with this PDF tutorial. Basics to advanced topics, including objects and methods, dynamic web pages and more. Perfect for beginners!


A guide to building a video game in Python

Get hands-on experience building a video game in Python with A Guide to Building a Video Game in Python PDF tutorial. Learn advanced concepts like Pygame and game development from scratch.


Python Tutorial

Download free course Python Tutorial, pdf file on 151 pages by Guido van Rossum and the Python development team.


JavaScript Front-End Web App Tutorial Part 4

Learn how to manage unidirectional associations between object types, such as the associations assigning publishers and authors to books, PDF file by Gerd Wagner.


Web Services with Examples

Download free An introduction to web services with exemples, course tutorial training, a PDF file by Hans-Petter Halvorsen.


Building Web Apps with Go

Download free course to learn how to build and deploy web applications with Go, PDF ebook by Jeremy Saenz.


Web application development with Laravel PHP Framework

Learn web development with Laravel PHP Framework through this free PDF tutorial. Discover Laravel's main features and build your first application.


Web Programming in Python with Django

Download free Web Programming in Python with Django, course tutorial training, PDF file by Steve Levine, Maria Rodriguez, Geoffrey Thomas.


Your First Node App: Build A Twitter Bot

Download tutorial Your First Node App Build A Twitter Bot, free PDF ebook by Emily Aviva.


A Short Introduction to Computer Programming Using Python

Download free ebook A Short Introduction to Computer Programming Using Python, PDF course on 34 pages.


Lightning Aura Components Developer Guide

Download free ebook Lightning Aura Components Developer Guide, UI framework for developing single page applications for mobile and desktop devices


Fundamentals of Python Programming

Download free course Fundamentals of Python Programming, pdf ebook tutorial on 669 pages by Richard L. Halterman.


J2EE Web Component Development

Download free J2EE Web Component Development course material training and tutorial, PDF file on 155 pages.


CakePHP Cookbook Documentation

Download free ebook CakePHP Cookbook Documentation a framework for web-development using PHP language, PDF file.


Getting Started with Dreamweaver CS6

Download free Getting Started with Dreamweaver CS6 course material, tutorial training, a PDF file on 32 pages.


Learning Python Language

Learning Python Language is a free PDF ebook with 206 chapters covering Python programming for both beginners and advanced learners.