go backBack to blog

Coding Your First Python Web App in 5 Minutes

Published on Apr 21 2024

Last updated on Apr 21 2024

Image by Pakata Goh on Unsplash
No translation available.
Add translation

First time coding in Python? Let me show you how to create your first webpage using Python, Flask, HTML and CSS.

Step 1: Install Python

Ensure Python is installed on your system. You can download it from the official Python website.

Step 2: Install Visual Studio Code

If you haven't installed VSCode yet, download and install it from here.

Step 3: Set Up Your Project

First, Create a new directory for your project and open it in VSCode:

bash

mkdir mywebapp
cd mywebapp
code .

Then, open the terminal in VSCode (you can open it via View -> Terminal or by pressing Ctrl+` ).

Step 4: Create a Virtual Environment

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

# For Windows
python -m venv venv
.\venv\Scripts\activate
# For macOS/Linux
python3 -m venv venv
source venv/bin/activate

  1. 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.

  2. 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) $).

Step 5: Install Flask

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).

Step 6: Create Your Flask Application

  1. Create a new Python file in your project directory, e.g., app.py.

  2. Add the following Python code to app.py to create a basic Flask application:

python

from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)

Step 7: Add HTML

  1. Create a folder named templates in your project directory.

  2. Create an HTML file within the templates folder, e.g., index.html.

  3. Write some HTML content in index.html. Here’s a simple example:

html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Web App</title>
</head>
<body>
<h1>Welcome to My Web App</h1>
<p>Hello, world! This is my first web app using Python and Flask.</p>
</body>
</html>

Step 8: Integrate CSS into Your Web App

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.

  1. Create a static folder in your project directory.

  2. 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

/mywebapp
/static
style.css
/templates
index.html
app.py
venv/

Open your style.css file and add some CSS rules. Here's a simple example to get you started:

css

body {
font-family: 'Arial', sans-serif;
background-color: #f4f4f9;
margin: 0;
padding: 0;
}
h1 {
color: #333;
text-align: center;
}
p {
margin: 20px;
text-align: center;
}

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

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Web App</title>
<!-- Link CSS in our HTML Template -->
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Welcome to My Web App</h1>
<p>Hello, world! This is my first web app using Python and Flask.</p>
</body>
</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.

Step 9: Define Additional Routes

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

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')
@app.route('/contact')
def contact():
return render_template('contact.html')
if __name__ == '__main__':
app.run(debug=True)

In this example, two new routes have been added: /about and /contact.

Step 10: Create Corresponding HTML Templates

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

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>About Us</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>About Us</h1>
<p>This is the about page. Here you can learn more about us.</p>
</body>
</html>

contact.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Us</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Contact Us</h1>
<p>You can contact us by email at info@example.com.</p>
</body>
</html>
Creating consistent and reusable webpage structure using Flask's templating features
1. Setting Up a Base Template

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.

2. Utilizing Flask's render_template Function

The 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.

3. Extending base.html in Other Templates

Each 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.

Consider Using URL Variables

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

@app.route('/user/<username>')
def show_user_profile(username):
# Show the user profile for that user
return f'User {username}'

This route will display any username entered in the URL at http://127.0.0.1:5000/user/<username>.

Step 11: Run Your Application

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.

Step 12: Refresh and Debug

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.

Conclusion

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!

Additional VSCode Extensions

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.

Tags:
front-end
tutorials
My portrait picture

Written by Alissa Nguyen

Alissa 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.

  • Photo by Steve Johnson on Unsplash
    Apr 06 2023 — 5 min readCSS Architecture: The Fundamentals
    #css#front-end
  • Photo by Nathan da Silva on Unsplash
    Sep 07 2022 — 5 min readIntroduction to HTML
    #front-end#html
  • Photo by Manja Vitolic
    Mar 27 2022 — 5 min readSetting up your custom domain with Namecheap and Netlify
    #front-end

  • Built and designed by Alissa Nguyen a.k.a Tam Nguyen.

    Copyright © 2024 All Rights Reserved.