seeb4coding python

How to Start with Python and Flask Framework

Flask is a powerful web framework for Python, ideal for building small to medium-sized web applications. In this blog, we’ll show you how to set up a Flask project, serve HTML, CSS, and JavaScript files, and manage routes for page redirection.


What is Flask?

Flask is a lightweight web framework for Python. Unlike frameworks like Django, Flask is minimalistic, giving developers flexibility to add only what they need for their application. In this post, you’ll learn how to set up your Flask project, handle static files (HTML, CSS, JS), and configure routes for redirection.


Step 1: Install Python

  • Download Python from https://www.python.org/downloads/.
  • Install it on your system, making sure to check the option to “Add Python to PATH”.
  • Verify the installation by running python -V in the terminal:
python -V

Step 2: Setting Up a Virtual Environment

To keep dependencies isolated, you’ll create a virtual environment:

Open a terminal in your project directory and run:

python -m venv .venv

Activate the virtual environment:

On Windows:

.venv\Scripts\activate

On macOS/Linux:

source .venv/bin/activate

Step 3: Installing Flask

With the virtual environment activated, install Flask:

pip install Flask

Step 4: Setting Up Folder Structure

Now, we’ll set up the folder structure for your Flask app, including directories for templates (HTML) and static files (CSS, JS, images).

Your folder structure should look like this:

/my_flask_app
    /static
        /css
            style.css
        /js
            script.js
    /templates
        index.html
    app.py
    .venv/
  • static/: Contains all your static files like CSS, JavaScript, and images.
  • templates/: Contains your HTML files.

Step 5: Creating HTML, CSS, and JS Files

  • index.html (inside the /templates folder):
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask App</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <h1>Welcome to Flask!</h1>
    <p>This is a simple Flask web app serving HTML, CSS, and JS files.</p>
    <button id="btn">Click me</button>
    
    <script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>
  • style.css (inside /static/css/):
body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    text-align: center;
    padding: 50px;
}
h1 {
    color: #333;
}
button {
    background-color: #28a745;
    color: white;
    padding: 10px 20px;
    border: none;
    cursor: pointer;
}
button:hover {
    background-color: #218838;
}
  • script.js (inside /static/js/):
document.getElementById('btn').addEventListener('click', () => {
    alert('Button clicked!');
});

Step 6: Writing Flask Code (app.py)

Now, we’ll modify the app.py file to render index.html and serve the static files (CSS, JS).

  • app.py:
from flask import Flask, render_template, redirect, url_for

app = Flask(__name__)

# Route for the homepage
@app.route('/')
def home():
    return render_template('index.html')

# Example of a redirect route
@app.route('/redirect-example')
def redirect_example():
    return redirect(url_for('home'))

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

Explanation:

  • render_template(): This function is used to render HTML files from the /templates folder.
  • Serving static files: In your HTML (index.html), Flask automatically knows to serve static files (CSS, JS, images) from the /static folder using url_for('static', filename='path/to/file').
  • Redirection: The redirect() function sends the user to a different route. In the example, /redirect-example redirects back to the homepage (/).

Step 7: Running the Application

Open your terminal, navigate to your project directory, and run:

python app.py

Flask will start the development server, and you’ll see output like this:

* Running on http://127.0.0.1:5000/

Open your web browser and visit http://127.0.0.1:5000/. You’ll see your styled web page with a functional button!

Try visiting http://127.0.0.1:5000/redirect-example/ to see how Flask handles redirection.


Conclusion

You’ve successfully set up a Flask project that serves HTML, CSS, and JavaScript files, and you’ve learned how to handle page redirection with Flask. With Flask’s minimalism and flexibility, you can easily expand this project to include multiple pages, forms, and much more.

For more advanced Flask features like database integration, form handling, and user authentication, refer to the Flask documentation.


Stay tuned for more tutorials where we dive deeper into building full-fledged web applications with Flask and Python!

Leave a Reply

Your email address will not be published. Required fields are marked *