Python Flask Tutorial: Creating Dynamic Database-Driven Web Apps for Web Development

Posted by


In this tutorial, we will explore how to create dynamic database-driven web applications using Flask, a popular web framework for Python. Flask is lightweight and flexible, making it an ideal choice for building small to medium-sized web applications.

Before we get started, make sure you have Python and Flask installed on your computer. You can install Flask using pip, the Python package manager, by running the following command in your terminal:

pip install Flask

You will also need a database management system such as SQLite, MySQL, or PostgreSQL to store and retrieve data for your web application. For the purposes of this tutorial, we will use SQLite, a lightweight database that is easy to set up and ideal for development and testing.

Step 1: Setting up the Flask application

Start by creating a new directory for your project and navigating to it in your terminal. Inside this directory, create a new Python file called app.py and open it in your preferred code editor.

In app.py, import Flask and create a new instance of the Flask application:

from flask import Flask

app = Flask(__name__)

Next, create a route for the home page of your web application:

@app.route('/')
def home():
    return 'Hello, World!'

Finally, run the Flask application by adding the following code at the bottom of app.py:

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

You can now run your Flask application by executing the app.py file in your terminal:

python app.py

Open a web browser and navigate to http://127.0.0.1:5000 to see the message "Hello, World!" displayed on the home page of your web application.

Step 2: Setting up the database

Before we can create dynamic database-driven web applications, we need to set up a database to store and retrieve data. For this tutorial, we will use SQLite, a lightweight database engine that does not require a separate server to run.

Create a new directory called data inside your project directory to store the SQLite database file. In app.py, import SQLite and create a new database connection:

import sqlite3

conn = sqlite3.connect('data/database.db')

Next, create a new SQLite database table to store some sample data. Add the following code to create a users table with id, name, and email columns:

with conn:
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT,
            email TEXT
        )
    ''')

Step 3: Adding dynamic routes

Now that we have set up the Flask application and database, let’s create some dynamic routes to interact with the database. Add the following code to app.py to create a route that retrieves all users from the database and displays them on a web page:

@app.route('/users')
def users():
    with conn:
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM users')
        users = cursor.fetchall()

    return f'Users: {users}'

You can now navigate to http://127.0.0.1:5000/users in your web browser to see a list of all users stored in the database.

Step 4: Adding a form to insert data

To allow users to insert new data into the database, we can create a form that submits data to the server. Add the following code to app.py to create a route that displays a form for users to enter their name and email:

from flask import request

@app.route('/add_user', methods=['GET', 'POST'])
def add_user():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']

        with conn:
            cursor = conn.cursor()
            cursor.execute('INSERT INTO users (name, email) VALUES (?, ?)', (name, email))

        return 'User added successfully!'

    return '''
        <form method="post">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name"><br>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email"><br>
            <input type="submit" value="Submit">
        </form>
    '''

Now, navigate to http://127.0.0.1:5000/add_user in your web browser to see a form that allows you to add new users to the database.

Step 5: Updating and deleting data

To allow users to update or delete data in the database, we can create additional routes that handle these actions. Add the following code to app.py to create routes for updating and deleting users:

@app.route('/update_user/<int:user_id>', methods=['GET', 'POST'])
def update_user(user_id):
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']

        with conn:
            cursor = conn.cursor()
            cursor.execute('UPDATE users SET name = ?, email = ? WHERE id = ?', (name, email, user_id))

        return 'User updated successfully!'

    with conn:
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))
        user = cursor.fetchone()

    return f'''
        <form method="post">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" value="{user[1]}"><br>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" value="{user[2]}"><br>
            <input type="submit" value="Submit">
        </form>
    '''

@app.route('/delete_user/<int:user_id>', methods=['GET', 'POST'])
def delete_user(user_id):
    with conn:
        cursor = conn.cursor()
        cursor.execute('DELETE FROM users WHERE id = ?', (user_id,))

    return 'User deleted successfully!'

You can now navigate to http://127.0.0.1:5000/update_user/<user_id> to update a specific user or http://127.0.0.1:5000/delete_user/<user_id> to delete a specific user from the database.

Congratulations! You have successfully created a dynamic database-driven web application using Flask and Python. Feel free to customize and expand upon this tutorial to create more complex web applications with additional features and functionality. Happy coding!

0 0 votes
Article Rating
50 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@jovianhq
2 months ago

We hope you enjoy this tutorial, and we look forward to seeing what you'll build! If you'd like to get your project reviewed by our team & earn a certificate, register here for free: https://jovian.com/learn/web-development-with-python-and-flask

If you have any questions or face issues, please post them in the comments and we'll help you out. Do check out our YouTube channel as well, where we're posting new tutorials every week.

Thanks @freecodecamp and Beau for hosting us! 🙏🏼

@acpucio
2 months ago

Thanks you Mr. Aakash for this wonderful tutorial.

@lhcunha1
2 months ago

Great lesson. Thanks!

@pythonically
2 months ago

continuously getting , This site can’t be reachedCheck if there is a typo in 092d17ff-c79f-4997-9a91-aadf0900ab0e-00-1dbtdgv0s4t27.sisko.replit.dev. why? when i run it very first time 20:00

@rockstarfeelmusic
2 months ago

why do we need to create a new repo(Jovian Carrers V2) instead of working with the same one(Jovian Carrers)???

Please Clarify this doubt!!

@aayushmaan3128
2 months ago

Planet scale stopped its hobby tier package what is a good alternative for it?

@lucky-xg4fv
2 months ago

Hello bro after i run the app.run code in th webview it is showing ip address could not fount what i need to so

@girishnaik6433
2 months ago

by far the most easy to understand tutorial I've come across

@germantoenglish898
2 months ago

I had to install python package at Replit for it to work. Otherwise I get a not found error. Took me an hour to figure it out but it's working now.

@pw-committee6960
2 months ago

some changes to avoid error in final touch

def add_application_to_db(job_id, data):
with engine.begin() as conn:
query = text("""
INSERT INTO applications (
job_id, full_name, email, linkedin_url, education, work_experience, resume_url
) VALUES (
:job_id, :full_name, :email, :linkedin_url, :education, :work_experience, :resume_url
)
""")

conn.execute(query, {
"job_id": job_id,
"full_name": data['full_name'],
"email": data['email'],
"linkedin_url": data['linkedin_url'],
"education": data['education'],
"work_experience": data['work_experience'],
"resume_url": data['resume_url']
})

@pw-committee6960
2 months ago

for (2:21:44) 2.2 Cloud MySQL Database Setup you may go with freesqldatabase free tier

@sujalbedre
2 months ago

4:19:02 The code of data:

def add_aplication_to_db(job_id, data):
with engine.connect() as conn:
query = text(
f"INSERT INTO applications(job_id, full_name, email, linkedin_url, education, work_experience, resume_url) VALUES (:job_id, :full_name, :email, :linkedin_url, :education, :work_experience, :resume_url)"
)

conn.execute(
query,
{
"job_id": job_id,
"full_name": data["full_name"],
"email": data["email"],
"linkedin_url": data["linkedin_url"],
"education": data["education"],
"work_experience": data["work_experience"],
"resume_url": data["resume_upload"],
},
)
conn.commit()

It will work definitely,

@Hillgrov
2 months ago

I skimmed though the tut.. I didn't see any end product.

@ggggggg98767
2 months ago

what a tutorial, started from zero, by the end got almost everything, on my way of building personal projects with obtained skills and knowledge!!

@thethtoozaw3371
2 months ago

the guy who looking for flask is already know about the basic HTML / CSS programming. Please fcking skip for these unnecessary lecture about HTML / CSS. it just waste of time for that guy.

@ayodeleadeynka4195
2 months ago

The tutorial was very impactful. Thank you for putting this togetter

@suchitajain7619
2 months ago

Hi Akash. Thank you for the detailed tutorial on Python web development. Specially delving into the very basics like HTML and CSS. It is a good refresher as well helped in learning Python web development as a whole.

@mathewtuwei1031
2 months ago

The best web development tutorial so far!
easy to Follow and understand.

@SHUBHAM-ko8bd
2 months ago

3:00:39

@ForRo3sS
2 months ago

This gentelman somehow has the best way for me to understand!