In this tutorial, we will learn how to create a web application using Flask, a lightweight web framework for Python. Flask allows us to quickly build web applications that are simple, scalable, and easy to understand.
To follow along with this tutorial, you should have a basic understanding of Python and web development concepts. Let’s get started!
Step 1: Set Up a Virtual Environment
First, we need to set up a virtual environment to isolate our project’s dependencies. This will ensure that our application runs consistently across different environments.
- Open your terminal or command prompt.
- Create a new directory for your project:
mkdir myapp
. - Navigate to the project directory:
cd myapp
. - Create a new virtual environment:
python3 -m venv venv
. - Activate the virtual environment:
- On macOS and Linux:
source venv/bin/activate
. - On Windows:
venvScriptsactivate
.
- On macOS and Linux:
Step 2: Install Flask
Now that we have our virtual environment set up, let’s install Flask.
- Make sure you are still in the project directory.
- Install Flask using pip:
pip install flask
.
Step 3: Create the Flask Application
With Flask installed, let’s create our Flask application.
- Create a new file called
app.py
in your project directory. - Open
app.py
in your favorite text editor.
In app.py
, we will import Flask and create our Flask application.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, Flask!'
In this code, we import the Flask
class and create an instance of it called app
. We then use the @app.route()
decorator to define a route for the root URL (“/”). When a user visits the root URL, the hello()
function will be called and it will return the string ‘Hello, Flask!’.
Step 4: Run the Flask Application
Now that we have our Flask application set up, let’s run it and see the results!
- Make sure you are still in the project directory.
- Start the Flask development server:
flask run
.
You should see output similar to the following:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Open your web browser and visit `http://127.0.0.1:5000/`. You should see the message ‘Hello, Flask!’ displayed on the page.
Congratulations! You have created a basic Flask web application.
Step 5: Routing and Templates
In the previous step, we defined a single route for the root URL. Let’s add more routes and use templates to render dynamic content.
- Update
app.py
with the following code:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/about')
def about():
return render_template('about.html')
- Create a new directory called
templates
in your project directory. - Inside the
templates
directory, create two files:index.html
andabout.html
.
In index.html
, add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome to the Home Page!</h1>
<p>Feel free to explore the website.</p>
</body>
</html>
In about.html
, add the following code:
<!DOCTYPE html>
<html>
<head>
<title>About</title>
</head>
<body>
<h1>About Us</h1>
<p>We are a team of developers passionate about Flask!</p>
</body>
</html>
Now, if you start the Flask development server again and visit http://127.0.0.1:5000/`, you will see the content from
index.html. If you visit
http://127.0.0.1:5000/about`, you will see the content from about.html
.
Flask uses the Jinja templating engine to render HTML templates. By using templates, we can separate our application logic from the presentation layer and create reusable components.
Step 6: Handling Form Data
To make our web application more interactive, let’s handle form data.
- Update
app.py
with the following code:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/contact', methods=['GET', 'POST'])
def contact():
if request.method == 'POST':
name = request.form.get('name')
email = request.form.get('email')
message = request.form.get('message')
# Process the form data (e.g. send an email, store in database)
return 'Thank you for your message, {}!'.format(name)
return render_template('contact.html')
- Inside the
templates
directory, create a new file calledcontact.html
.
In contact.html
, add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Contact</title>
</head>
<body>
<h1>Contact Us</h1>
<form method="POST" action="/contact">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<button type="submit">Submit</button>
</form>
</body>
</html>
Now, when you visit http://127.0.0.1:5000/contact`, you will see a form where you can enter your name, email, and message. When you submit the form, the form data will be sent to the
/contact` route where it will be processed. In this example, we simply return a thank you message to the user.
Step 7: Adding Static Files
Flask also makes it easy to serve static files such as CSS stylesheets, JavaScript files, and images.
- Create a new directory called
static
in your project directory. - Inside the
static
directory, create a file calledstyles.css
.
In styles.css
, add some CSS code:
body {
font-family: Arial, sans-serif;
}
h1 {
color: #ff0000;
}
p {
color: #0000ff;
}
To use this stylesheet in your templates, update index.html
and about.html
as follows:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<h1>Welcome to the Home Page!</h1>
<p>Feel free to explore the website.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>About</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<h1>About Us</h1>
<p>We are a team of developers passionate about Flask!</p>
</body>
</html>
Restart the Flask development server and refresh the pages. You should see the text styled according to the CSS rules.
Conclusion
In this tutorial, we covered the basics of creating a web application with Flask and Python. We learned how to set up a virtual environment, install Flask, create routes, use templates, handle form data, and serve static files.
Flask provides a powerful yet simple way to create web applications in Python. By following this tutorial, you should now have a good foundation to build upon and create more complex applications.
Keep practicing and experimenting with Flask to explore its full potential. Happy coding!