How To Create A Static Website In Python With Flask

Step-by-Step Guide:

To create a static website in Python, you can use a web framework such as Flask or Django. Here’s a step-by-step guide on how to create a basic static website using Flask:

Set up a virtual environment (optional but recommended):

  1. Open your terminal or command prompt.
  2. Create a new directory for your project and navigate to it.
  3. Create a virtual environment by running: `python3 -m venv myenv`
  4. Activate the virtual environment:
    – On Windows: `myenv\Scripts\activate`
    – On macOS/Linux: `source myenv/bin/activate`

Install Flask:

– While in the virtual environment, run: `pip install flask`

Create a new Python file, let’s call it `app.py`, and open it in a text editor.

Importing:

First import Flask and create an instance of the Flask application:

python
from flask import Flask

app = Flask(__name__)

Defining Route

Define a route for the homepage (“/”) and a corresponding function that returns the HTML content:

python
@app.route('/')
def home():
return '<h1>Welcome to my static website!</h1>'

Save the file.

Terminal

In your terminal or command prompt, make sure you are in the project directory and run the Flask development server:

flask run

Output

You should see an output indicating that the development server is running. Open a web browser and enter `http://localhost:5000` in the address bar.

Congratulations!

Voila! You should see the HTML content you defined in the `home` function displayed in the browser.

Adding more pages

To add more pages or routes, simply define additional functions with corresponding route decorators.

Additionally:

To include external CSS or JavaScript files, create a directory called “static” in your project directory and place the files inside it. Then, you can reference them in your HTML templates using the `url_for` function provided by Flask.

This is a basic example to get you started with a static website in Python using Flask. You can expand upon it by using HTML templates, organizing your routes into separate files, and adding more complex functionality as needed.

Leave a comment