Developing Dynamic Web Apps with Python, Flask, and MySQL

Python, Flask and MySQL logos

Are you a Python developer looking to build dynamic, database-driven web applications? Combining the Python programming language with the Flask web framework and MySQL database allows you to quickly develop powerful web apps that can store and retrieve data. In this guide, we‘ll walk through the process of building a database-driven web application from scratch using these tools and technologies.

Setting Up Your Development Environment

Before we dive in, let‘s make sure you have Python and MySQL installed on your machine:

  1. Download and install Python (version 3.6 or higher is recommended). During installation, be sure to check the box to add Python to your PATH.

  2. Download and run the MySQL installer for your operating system. This will guide you through installing the MySQL server and other tools. Make note of the root password you set during installation.

Next, create a new directory for your project, and set up a Python virtual environment inside it:

mkdir my-flask-app
cd my-flask-app
python -m venv venv

Activate the virtual environment:

# Windows   
venv\Scripts\activate

# Linux/Mac
source venv/bin/activate  

Now use pip to install Flask and the Flask-SQLAlchemy extension for interacting with databases:

pip install flask flask-sqlalchemy

With our development environment ready, let‘s start building our application!

A Sneak Peek of Flask

Flask is a lightweight and flexible Python web framework that provides useful tools and features for creating web applications.

Here‘s a minimal Flask application in a file named app.py:

from flask import Flask

app = Flask(__name__)

@app.route(‘/‘)
def hello():
    return ‘Hello, World!‘

This code creates a new Flask application instance, and defines a route that maps the URL path / to a view function hello(), which returns the string ‘Hello, World!‘.

You can run this app from the terminal with:

flask run

Then visit http://localhost:5000 in your web browser to see "Hello, World!" displayed.

This is just a taste of what Flask can do. It also provides an integrated development server, interactive debugger, and support for unit testing. Flask embraces a modular design, allowing developers to choose the tools and libraries they want to use in their projects.

Working with Databases in Python

Most web apps need to store and retrieve data, and relational databases like MySQL are a great choice for this. They provide a structured way to organize information into tables of rows and columns. Interactions with the database are performed using SQL (Structured Query Language).

Python‘s database API allows you to interface with relational databases like MySQL. You can connect to a database, execute queries, and handle result sets.

Here‘s an example of how to connect to a MySQL database and execute a query using Python‘s built-in mysql.connector module:

import mysql.connector

db = mysql.connector.connect(
  host="localhost",
  user="root", 
  password="secret",
  database="example"
)

cursor = db.cursor()

cursor.execute("SELECT * FROM users")

for row in cursor:
  print(row)

db.close()

While you can use raw SQL queries in your Flask apps, it‘s often more convenient to use an ORM (Object-Relational Mapping) tool like SQLAlchemy. An ORM maps database tables to Python classes, allowing you to interact with your database using familiar object-oriented programming techniques.

Here‘s that same example using Flask-SQLAlchemy:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config[‘SQLALCHEMY_DATABASE_URI‘] = ‘mysql://root:secret@localhost/example‘
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return ‘<User %r>‘ % self.username

@app.route(‘/users‘)
def users():
    users = User.query.all()
    return str(users)

In this example, we configure Flask-SQLAlchemy with the URI for our MySQL database. We then define a User model that maps to a users table. The users() view function retrieves all user records from the database and returns them as a string.

Using an ORM like SQLAlchemy can save a lot of time and simplify database interactions in your web apps. It provides a high-level abstraction over SQL and the database, while still allowing you to drop down to writing raw queries if needed.

Building a Database-Driven Flask Application

Now let‘s put these pieces together and build a simple Flask application that allows users to view and add quotes to a MySQL database.

We‘ll start by designing our database schema. We need a quotes table to store our quotes:

CREATE TABLE quotes (
    id INT AUTO_INCREMENT PRIMARY KEY,
    author VARCHAR(100) NOT NULL,
    quote TEXT NOT NULL
);

Next, let‘s set up our Flask app to connect to this database and define a SQLAlchemy model for the quotes table:

from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config[‘SQLALCHEMY_DATABASE_URI‘] = ‘mysql://root:secret@localhost/quotedb‘
db = SQLAlchemy(app)

class Quote(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author = db.Column(db.String(100), nullable=False)
    quote = db.Column(db.Text, nullable=False)

    def __repr__(self):
        return f"<Quote {self.id}>"

We‘ll define two view functions. The first one will retrieve all quotes from the database and render them using an HTML template:

@app.route(‘/‘)
def index():
    quotes = Quote.query.all()
    return render_template(‘index.html‘, quotes=quotes)

The index.html template might look something like this:

<!DOCTYPE html>
<html>
<head>
    <title>Quotes</title>
</head>
<body>

    <ul>
        {% for quote in quotes %}
            <li>"{{ quote.quote }}" - {{ quote.author }}</li>
        {% endfor %}
    </ul>
    <a href="/add">Add a new quote</a>
</body>
</html>

The second view function will handle adding new quotes to the database:

@app.route(‘/add‘, methods=[‘GET‘, ‘POST‘])
def add():
    if request.method == ‘POST‘:
        author = request.form[‘author‘]
        quote = request.form[‘quote‘]
        new_quote = Quote(author=author, quote=quote)
        db.session.add(new_quote)
        db.session.commit()
        return redirect(‘/‘)
    else:
        return render_template(‘add.html‘)

This function checks if the request method is POST, indicating that the user submitted the form. If so, it retrieves the form data, creates a new Quote object, adds it to the database session, and commits the transaction. Finally, it redirects back to the home page.

If the request method is GET, it simply renders the add.html template containing the form:

<!DOCTYPE html>
<html>
<head>
    <title>Add a Quote</title>
</head>
<body>

    <form method="post">
        <label for="author">Author:</label>
        <input type="text" id="author" name="author" required>
        <br>
        <label for="quote">Quote:</label>
        <textarea id="quote" name="quote" required></textarea>
        <br>
        <button type="submit">Add</button>
    </form>
</body>
</html>

That‘s it! You now have a functional web application that allows users to view and add quotes, with the data stored in a MySQL database.

Of course, there‘s a lot more you could do to expand this application, such as editing or deleting quotes, adding user authentication, improving the design with CSS, or paginating the quotes list. But this example demonstrates the fundamental architecture for a database-driven Flask app.

Deploying Your Flask Application

Once you‘ve developed your Flask app, you‘ll probably want to deploy it so others can use it. There are many options for deploying Python web applications, from traditional server hosting to cloud platforms.

One popular choice is PythonAnywhere, a Python-focused cloud hosting service. It provides a free tier that‘s great for small apps and testing. Here‘s a quick guide to deploying your Flask app on PythonAnywhere:

  1. Sign up for a free PythonAnywhere account.
  2. Open a Bash console from your PythonAnywhere dashboard.
  3. Clone your Flask app‘s Git repository (or upload your application files).
  4. Create a virtual environment and install your app‘s dependencies:
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt  
  1. Set up your MySQL database using the PythonAnywhere MySQL interface.
  2. Configure your Flask app for production by setting the SECRET_KEY and SQLALCHEMY_DATABASE_URI environment variables.
  3. Create a new web app from your PythonAnywhere dashboard, specifying the path to your Flask app‘s entry point.
  4. Reload your web app, and visit your PythonAnywhere-hosted URL to see your live Flask app!

For more detailed deployment guides and other hosting options, check out the Flask Deployment documentation.

Conclusion

Building database-driven web applications with Python, Flask, and MySQL is a powerful way to create dynamic, data-centric websites and services. Flask provides a solid foundation with its built-in development server, routing, templating, and extensible design. MySQL is a robust and widely-used relational database that integrates well with Python and Flask. The SQLAlchemy ORM simplifies database interactions and allows you to focus on your application logic.

To learn more about these tools and technologies, consult the following resources:

I hope this guide has provided a helpful introduction to building database-driven web apps with Python, Flask, and MySQL. Happy coding!

Similar Posts