Are you tired of writing the same boilerplate code over and over again for your web applications? Well, my friend, have I got a treat for you. Introducing Flask: The lightweight WSGI microframework that will change the way you think about building web apps in Python.
Flask is not like those bloated frameworks out there that make you feel like you’re drowning in a sea of configuration options and boilerplate code. No, sir! Flask is simple, elegant, and easy to use. It’s the perfect choice for small-to-medium sized web applications where you don’t need all the bells and whistles that come with those other frameworks.
So, let’s dive right in and see how we can build a basic Flask app from scratch! To begin with: install Flask using pip (or your favorite package manager). If you haven’t already done so, make sure to create a virtual environment for this project. Trust me, it will save you headaches down the road.
# Create a directory for the Flask app and navigate into it
$ mkdir my-flask-app && cd $_
# Create a virtual environment for the project
$ python3 -m venv env
# Activate the virtual environment
$ source env/bin/activate
# Install Flask using pip
(env) $ pip install Flask
# Explanation:
# The first line creates a directory for the Flask app and navigates into it.
# The second line creates a virtual environment for the project.
# The third line activates the virtual environment.
# The fourth line installs Flask using pip within the virtual environment.
Now that we have Flask installed, let’s create a new file called `app.py`. This will be our main application module where all the magic happens. Open up your favorite text editor and add this code:
# Import the Flask module
from flask import Flask
# Create an instance of the Flask class and assign it to the variable "app"
app = Flask(__name__)
# Use the route decorator to specify the URL path for the following function
@app.route('/')
# Define a function named "hello_world" that returns a string
def hello_world():
return 'Hello, World!'
# Check if the script is being run directly and not imported as a module
if __name__ == "__main__":
# Run the application in debug mode
app.run(debug=True)
This code creates a new instance of the Flask class and sets up our first route (the root URL). When someone visits `http://localhost:5000`, they will see “Hello, World!” displayed on their screen. Pretty cool, huh?
Let’s add some basic styling to make this app look a little nicer. Create a new file called `static/css/style.css` and add the following code:
/* This is a CSS script that adds basic styling to an app. It targets the body and h1 elements and applies specific styles to them. */
/* The following code sets the font family for the entire body of the app to Arial or any sans-serif font. */
body {
font-family: Arial, sans-serif;
}
/* The following code centers the text within the h1 element. */
h1 {
text-align: center;
}
Now let’s modify our Flask app to serve static files. Add this line of code at the top of `app.py`:
# Import the Flask and render_template modules from the flask library
from flask import Flask, render_template
# Create a Flask application instance
app = Flask(__name__)
# Define a route for the root URL of the application
@app.route('/')
def index():
# Render the index.html template
return render_template('index.html')
# Define a route for serving static files
@app.route('/static/<path:filename>')
def serve_static(filename):
# Return the static file requested by the client
return app.send_static_file(filename)
# Run the application on the local development server
if __name__ == '__main__':
# Set the debug mode to True for automatic reloading
app.run(debug=True)
# Explanation:
# - The first line imports the Flask and render_template modules from the flask library.
# - The second line creates a Flask application instance.
# - The third line defines a route for the root URL of the application.
# - The fourth line uses the render_template function to render the index.html template.
# - The fifth line defines a route for serving static files.
# - The sixth line uses the send_static_file function to return the static file requested by the client.
# - The seventh line runs the application on the local development server.
# - The eighth line sets the debug mode to True for automatic reloading.
And replace the existing route with this new one:
# This is a Flask route decorator that specifies the URL path for the following function
@app.route('/')
# This function is called when a GET request is made to the specified URL path
def hello_world():
# This function returns the rendered template 'index.html'
return render_template('index.html')
Create a new file called `templates/index.html` and add the following code:
<!--
The following script creates a new html file called "index.html" and adds the necessary code for a Flask application.
-->
<!DOCTYPE html> <!-- This line specifies the document type as HTML -->
<html lang="en"> <!-- This line specifies the language of the document as English -->
<head> <!-- This section contains the metadata for the document -->
<meta charset="UTF-8"> <!-- This line specifies the character encoding for the document as UTF-8 -->
<title>Flask App</title> <!-- This line sets the title of the document to "Flask App" -->
{% extends 'base.html' %} <!-- This line extends the base template for the document -->
</head>
<body> <!-- This section contains the body of the document -->
{{ content }} <!-- This line inserts the content from the Flask application into the document -->
</body>
</html> <!-- This line closes the html tag and ends the document -->
This code uses Jinja2 to extend a base template (which we haven’t created yet). We also pass the `content` variable, which will be filled in by Flask when it renders this template.
Create another file called `templates/base.html` and add the following code:
<!DOCTYPE html> <!-- This line declares the document type as HTML -->
<html lang="en"> <!-- This line declares the language of the document as English -->
<head>
<meta charset="UTF-8"> <!-- This line specifies the character encoding for the document -->
<title>{% block title %}{{ app_name }} Flask App{% endblock %}</title> <!-- This line uses Jinja2 to set the title of the page, which will be filled in by Flask when it renders this template -->
{% if static_url %} <!-- This line checks if the variable "static_url" exists -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"> <!-- This line creates a link to a CSS file, using the Flask function "url_for" to generate the correct URL for the file -->
{% endif %}
</head>
<body>
{{ content }} <!-- This line inserts the content variable, which will be filled in by Flask when it renders this template -->
</body>
</html>
This code sets up a base template that includes the title of our app (which we will define in `app.py`) and links to any static files we have defined.
Finally, let’s modify `app.py` one last time:
# This code sets up a Flask application and configures it with necessary settings.
# Import the Flask module and render_template function from flask library.
from flask import Flask, render_template
# Import the os module to access operating system functionalities.
import os
# Create an instance of the Flask application.
app = Flask(__name__)
# Set the TEMPLATES_AUTO_RELOAD configuration to True to automatically reload templates when they are modified.
app.config['TEMPLATES_AUTO_RELOAD'] = True
# Set the DEBUG configuration to True to enable debugging mode.
app.config['DEBUG'] = True
# Set the STATIC_URL_PATH configuration to specify the URL path for static files.
app.config['STATIC_URL_PATH'] = '/static'
# Set the STATIC_FOLDER configuration to specify the folder where static files are located.
app.config['STATIC_FOLDER'] = 'static'
# Define a route for the root URL.
@app.route('/')
def hello_world():
# Render the index.html template and pass in the app_name variable with the value 'Flask App'.
return render_template('index.html', app_name='Flask App')
# Run the application in debug mode.
if __name__ == "__main__":
app.run(debug=True)
This code sets up some configuration options for Flask, including enabling template auto-reloading and debug mode. We also set the URL path and folder for our static files.
And that’s it! You now have a basic Flask web application with styling and dynamic content. Pretty cool, huh? Of course, this is just scratching the surface of what you can do with Flask. There are countless libraries and extensions available to help you build more complex applications. But for now, let’s celebrate our victory over bloated frameworks!
Flask: The Lightweight WSGI Microframework That Will Change Your Life (Or At Least Your Python Web App Development)
Are you tired of writing the same boilerplate code over and over again for your web applications? Do you want a lightweight, easy-to-use framework that won’t bog you down with unnecessary configuration options? Well, my friend, have I got news for you! Introducing Flask: The WSGI microframework that will change the way you think about building web apps in Python.
Flask is not like those bloated frameworks out there that make you feel like you’re drowning in a sea of configuration options and boilerplate code. No, sir! Flask is simple, elegant, and easy to use. It’s the perfect choice for small-to-medium sized web applications where you don’t need all the bells and whistles that come with those other frameworks.