Published on Apr 21 2024
Last updated on Apr 21 2024
First time coding in Python? Let me show you how to create your first webpage using Python, Flask, HTML and CSS.
Ensure Python is installed on your system. You can download it from the official Python website.
If you haven't installed VSCode yet, download and install it from here.
First, Create a new directory for your project and open it in VSCode:
bash
1mkdir mywebapp2cd mywebapp3code .
Then, open the terminal in VSCode (you can open it via View -> Terminal
or by pressing Ctrl+`
).
It's good practice to create a virtual environment for your Python projects. This keeps dependencies required by different projects separate by creating isolated Python environments for them.
bash
1# For Windows2python -m venv venv3.\venv\Scripts\activate45# For macOS/Linux6python3 -m venv venv7source venv/bin/activate
python3 -m venv venv
This command creates a new virtual environment named venv
using the built-in venv
module in Python 3.
A virtual environment is an isolated Python environment that allows you to install and manage packages separately from your system's global Python installation.
The -m
flag is used to run a module as a script.
venv
is the name of the module you're running, which is the built-in module for creating virtual environments.
venv
is the name you're giving to your new virtual environment.
source venv/bin/activate
This command activates the virtual environment you just created.
source
is a bash command that reads and executes commands from a specified file.
venv/bin/activate
is the path to the activation script for your virtual environment.
On Windows, you would use venv\Scripts\activate
instead.
After running this command, your terminal prompt should change to indicate that the virtual environment is active (e.g., (venv) $
).
With your virtual environment activated, install Flask using pip: pip install Flask
.
What is Flask?
Flask is a lightweight, open-source Python web framework designed for building web applications. It is a micro-framework, which means it comes with a minimal set of tools and libraries, and it is designed to be easy to use and extend with third-party libraries and modules. It offers these key features:
Routing: Flask provides a routing mechanism that allows you to map URLs to Python functions, making it easy to handle different HTTP requests (GET, POST, etc.) and create dynamic web pages.
Templating Engine: Flask comes with a built-in templating engine called Jinja2, which allows you to create HTML templates and dynamically insert data into them.
Request Handling: Flask makes it easy to handle incoming HTTP requests, access form data, query parameters, headers, and cookies.
Debugging: Flask includes a built-in development server and a debugger, which makes it easier to test and debug your application during development.
RESTful Request Dispatching: Flask supports RESTful request dispatching, which makes it suitable for building APIs and RESTful web services.
Extensibility: Flask is designed to be extensible, which means you can add third-party libraries and extensions to enhance its functionality. This includes libraries for database integration, authentication, caching, and more.
Flask is suitable for building small to medium-sized web applications, APIs, and microservices. It is often used in conjunction with other Python libraries and tools, such as SQLAlchemy (for database integration), Flask-RESTful (for building RESTful APIs), and Flask-WTF (for form handling).
Create a new Python file in your project directory, e.g., app.py
.
Add the following Python code to app.py
to create a basic Flask application:
python
1from flask import Flask, render_template23app = Flask(__name__)45@app.route('/')6def home():7return render_template('index.html')89if __name__ == '__main__':10app.run(debug=True)
Create a folder named templates
in your project directory.
Create an HTML file within the templates
folder, e.g., index.html
.
Write some HTML content in index.html
. Here’s a simple example:
html
1<!DOCTYPE html>2<html lang="en">3<head>4<meta charset="UTF-8">5<meta name="viewport" content="width=device-width, initial-scale=1.0">6<title>My Web App</title>7</head>8<body>9<h1>Welcome to My Web App</h1>10<p>Hello, world! This is my first web app using Python and Flask.</p>11</body>12</html>
Now that you got the basic structure of the web app, we can start integrating CSS into our Flask application in VSCode.
CSS files are typically considered static files in the context of a web application. Flask handles static files (like CSS, JavaScript, and images) by serving them from a folder conventionally named static
.
Create a static
folder in your project directory.
Inside the static
folder, create a new CSS file. For example, you might call it
style.css
.
Here’s how your project directory might look now:
bash
1/mywebapp2/static3style.css4/templates5index.html6app.py7venv/
Open your style.css
file and add some CSS rules. Here's a simple example to get you started:
css
1body {2font-family: 'Arial', sans-serif;3background-color: #f4f4f9;4margin: 0;5padding: 0;6}78h1 {9color: #333;10text-align: center;11}1213p {14margin: 20px;15text-align: center;16}
This CSS will style the body background, and the text alignment and color of headers and paragraphs.
To use the CSS file you created, you need to link it in your HTML file(s). Open your index.html
in the templates
folder and link your CSS file using the <link>
tag within the <head>
section of the HTML. Flask provides a helper function, url_for
, to generate URLs for static files dynamically.
Here’s how you can modify index.html
to include the CSS file:
html
1<!DOCTYPE html>2<html lang="en">3<head>4<meta charset="UTF-8">5<meta name="viewport" content="width=device-width, initial-scale=1.0">6<title>My Web App</title>7<!-- Link CSS in our HTML Template -->8<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">9</head>10<body>11<h1>Welcome to My Web App</h1>12<p>Hello, world! This is my first web app using Python and Flask.</p>13</body>14</html>
The url_for('static', filename='style.css')
function tells Flask to look for a file named style.css
in the static
directory.
If you want to learn how to add routes in your Flask web app, continue to the next step. If you are only making a single-route application, skip step 9-10.
Adding routes in a Flask web application allows you to create different pages or functionalities accessible via distinct URLs. Each route is associated with a Python function, and when a specific URL is accessed, the corresponding function is executed, and its response is sent back to the client.
In Flask, routes are defined using the @app.route()
decorator above a function. Each function then provides the response for its route. Here's an example of adding a couple of new routes to your existing Flask application:
Open your app.py
file and modify it as follows:
app.py
1from flask import Flask, render_template23app = Flask(__name__)45@app.route('/')6def home():7return render_template('index.html')89@app.route('/about')10def about():11return render_template('about.html')1213@app.route('/contact')14def contact():15return render_template('contact.html')1617if __name__ == '__main__':18app.run(debug=True)
In this example, two new routes have been added: /about
and /contact
.
For each new route, create an HTML template in the templates
directory. This is where you'll define the HTML that should be rendered when each route is accessed.
about.html
1<!DOCTYPE html>2<html lang="en">3<head>4<meta charset="UTF-8">5<meta name="viewport" content="width=device-width, initial-scale=1.0">6<title>About Us</title>7<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">8</head>9<body>10<h1>About Us</h1>11<p>This is the about page. Here you can learn more about us.</p>12</body>13</html>
contact.html
1<!DOCTYPE html>2<html lang="en">3<head>4<meta charset="UTF-8">5<meta name="viewport" content="width=device-width, initial-scale=1.0">6<title>Contact Us</title>7<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">8</head>9<body>10<h1>Contact Us</h1>11<p>You can contact us by email at info@example.com.</p>12</body>13</html>
Create a base.html
file in your templates
folder.
This file serves as the skeleton for all other pages in the application. It includes common elements that appear on every page, such as the navigation bar (navbar) and the basic HTML structure (like the head
and body
tags).
This approach eliminates the need to repeat the same HTML code in every template, promoting DRY (Don't Repeat Yourself) principles and making the codebase easier to maintain and update.
render_template
FunctionThe render_template
function is used in each route handler in app.py
to generate the final HTML response that the client sees. This function takes the name of a template and a context (variables that should be available in the template) and renders the template into HTML. In our case, each route handler specifies which template to render—whether it's index.html
, about.html
, or contact.html
.
base.html
in Other TemplatesEach specific page template (index.html
, about.html
, contact.html
) extends base.html
using Jinja2's {% extends %}
tag. These child templates define content specific to each page within blocks designated by {% block %}
tags in base.html
. This structure allows each page to inject its unique content (like the main text and headers) into the predefined blocks of the base template.
With this templating approach, we enhance the maintainability and scalability of the web application. Changes to the overall page structure or style can be made in just one place (base.html
or style.css
), and these changes will automatically apply to all pages in the application. Additionally, adding new pages is as simple as creating a new template that extends base.html
and adding a corresponding route in app.py
. For the specific code and example, visit the source code.
With the new routes and templates added, run your Flask application by executing python app.py
.
This will start the Flask development server. You can then visit http://127.0.0.1:5000/
in your browser to access the home page, and add /about
or /contact
to the URL to visit the new pages.
Flask also allows you to capture parts of the URL as variables, which can be dynamic and used within your route functions. Here's an example of how you can use a variable in a route:
python
1@app.route('/user/<username>')2def show_user_profile(username):3# Show the user profile for that user4return f'User {username}'
This route will display any username entered in the URL at http://127.0.0.1:5000/user/<username>
.
Back in your terminal (make sure your virtual environment is activated), run the Flask application: python app.py
.
Flask will start a web server on localhost
at port 5000
. Open your web browser and go to http://127.0.0.1:5000/
to see your webpage.
When you make changes to your Flask app, ensure your server is running with debug=True
as it allows the server to reload itself on code changes, and provides a debugger if things go wrong.
And here you go! Congratulations on creating your first web application with Python and Flask. I hope you learn something new in this article. See you again in the next blog post!
Consider installing the following extensions in VSCode to help with your development:
Python extension for Visual Studio Code (official extension from Microsoft).
Flask Snippets to help speed up Flask development.
HTML CSS Support and IntelliSense for CSS class names in HTML for better HTML and CSS integration.
Written by Alissa Nguyen
FollowAlissa Nguyen is a software engineer with main focus is on building better software with latest technologies and frameworks such as Remix, React, and TailwindCSS. She is currently working on some side projects, exploring her hobbies, and living with her two kitties.
Learn more about me
If you found this article helpful.
You will love these ones as well.
Built and designed by Alissa Nguyen a.k.a Tam Nguyen.
Copyright © 2024 All Rights Reserved.