Building Your First Flask App: A Beginner's Guide

Building Your First Flask App: A Beginner's Guide Flask is a lightweight and powerful web framework for Python. In this guide, we’ll walk you through building your first Flask app, complete with user authentication (signup and login). By the end, you’ll have a fully functional app running on your local machine. Prerequisites Before we start, make sure you have the following: Python installed (version 3.7 or higher) Basic knowledge of Python A code editor (e.g., VS Code) MySQL installed locally or access to a MySQL database A willingness to learn (and maybe some coffee ☕) Step 1: Setting Up Your Environment Install Flask: lask is a tool that helps us build websites using Python. To install it, open your terminal and run: pip install flask flask-mysqldb werkzeug Create Your Project Directory: Think of this as creating a folder where all your files will live. Run: mkdir myfirstFlaskApp cd myfirstFlaskApp Set Up Your Database: Create a MySQL database named myDB and a table named user: CREATE DATABASE myDB; USE myDB; CREATE TABLE user ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(100) UNIQUE, password VARCHAR(255) ); Step 2: Writing the Flask App Create a file named app.py and add the following code: from flask import Flask, render_template, request, flash, redirect, url_for, session from flask_mysqldb import MySQL from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) # MySQL Config app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = 'your_mysql_password' app.config['MYSQL_DB'] = 'myDB' mysql = MySQL(app) app.secret_key = 'your_secret_key' @app.route('/') def home(): return render_template('index.html') @app.route('/signup', methods=['GET', 'POST']) def signup(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] hashed_password = generate_password_hash(password) try: cur = mysql.connection.cursor() cur.execute("INSERT INTO user (username, password) VALUES (%s, %s)", (username, hashed_password)) mysql.connection.commit() cur.close() flash('Registration successful!', 'success') return redirect(url_for('login')) except: flash('Registration failed! Username might already exist.', 'error') return render_template('signup.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] cur = mysql.connection.cursor() cur.execute("SELECT * FROM user WHERE username = %s", [username]) user = cur.fetchone() cur.close() if user and check_password_hash(user[2], password): session['username'] = username flash('Welcome back, {}!'.format(username), 'success') return redirect(url_for('home')) else: flash('Invalid username or password', 'danger') return render_template('login.html') if __name__ == '__main__': app.run(debug=True) Step 3: Creating the HTML Templates Homepage (templates/index.html): Home Page {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} {{ message }} {% endfor %} {% endif %} {% endwith %} Welcome to My Flask App This is the homepage. Signup Login Signup Page (templates/signup.html): Signup {% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} {% endwith %} Signup Username Password Register Login Page (templates/login.html): Login {% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} {% endwith %} Login

Apr 9, 2025 - 19:16
 0
Building Your First Flask App: A Beginner's Guide

Building Your First Flask App: A Beginner's Guide

Flask is a lightweight and powerful web framework for Python. In this guide, we’ll walk you through building your first Flask app, complete with user authentication (signup and login). By the end, you’ll have a fully functional app running on your local machine.

Let's Code

Prerequisites

Before we start, make sure you have the following:

  • Python installed (version 3.7 or higher)
  • Basic knowledge of Python
  • A code editor (e.g., VS Code)
  • MySQL installed locally or access to a MySQL database
  • A willingness to learn (and maybe some coffee ☕)

Step 1: Setting Up Your Environment

  1. Install Flask: lask is a tool that helps us build websites using Python. To install it, open your terminal and run:
   pip install flask flask-mysqldb werkzeug
  1. Create Your Project Directory: Think of this as creating a folder where all your files will live. Run:
   mkdir myfirstFlaskApp
   cd myfirstFlaskApp
  1. Set Up Your Database: Create a MySQL database named myDB and a table named user:
   CREATE DATABASE myDB;
   USE myDB;
   CREATE TABLE user (
       id INT AUTO_INCREMENT PRIMARY KEY,
       username VARCHAR(100) UNIQUE,
       password VARCHAR(255)
   );

Step 2: Writing the Flask App

Create a file named app.py and add the following code:

from flask import Flask, render_template, request, flash, redirect, url_for, session
from flask_mysqldb import MySQL
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)

# MySQL Config
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'your_mysql_password'
app.config['MYSQL_DB'] = 'myDB'
mysql = MySQL(app)

app.secret_key = 'your_secret_key'

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        hashed_password = generate_password_hash(password)

        try:
            cur = mysql.connection.cursor()
            cur.execute("INSERT INTO user (username, password) VALUES (%s, %s)", (username, hashed_password))
            mysql.connection.commit()
            cur.close()
            flash('Registration successful!', 'success')
            return redirect(url_for('login'))
        except:
            flash('Registration failed! Username might already exist.', 'error')
    return render_template('signup.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        cur = mysql.connection.cursor()
        cur.execute("SELECT * FROM user WHERE username = %s", [username])
        user = cur.fetchone()
        cur.close()

        if user and check_password_hash(user[2], password):
            session['username'] = username
            flash('Welcome back, {}!'.format(username), 'success')
            return redirect(url_for('home'))
        else:
            flash('Invalid username or password', 'danger')
    return render_template('login.html')

if __name__ == '__main__':
    app.run(debug=True)

Step 3: Creating the HTML Templates

  1. Homepage (templates/index.html):
   
    lang="en">
   
        charset="UTF-8">
        name="viewport" content="width=device-width, initial-scale=1.0">
       </span>Home Page<span class="nt">
        rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
   
   
        class="container mt-5">
           {% with messages = get_flashed_messages(with_categories=true) %}
               {% if messages %}
                   {% for category, message in messages %}
                        class="alert alert-{{ category }}">{{ message }}
{% endfor %} {% endif %} {% endwith %} class="text-center">

Welcome to My Flask App

This is the homepage. class="btn-group"> href="/signup" class="btn btn-primary">Signup href="/login" class="btn btn-success">Login