Flask Web Development for Intermediate Pythonistas
Flask Basics
What is Flask?
Flask is a Python web framework. Think of a framework as a toolkit that gives you helpful components to build websites and web applications. Instead of starting from scratch, you get a solid foundation to build upon.
Flask is known as a "micro" framework. This doesn't mean it's less powerful, but that it's small and flexible. It provides the essentials for getting a web server running and handling user requests, but it doesn't force you to use specific tools for things like database access or form validation. You get to choose the parts you need, which makes it a great starting point for learning web development.
Flask is a lightweight and flexible Python web framework that allows developers to build web applications quickly and efficiently.
Setting Up Your Environment
Before installing Flask, it's a best practice to create a virtual environment. This is an isolated space for your project that keeps its dependencies separate from other Python projects on your system. It prevents conflicts between packages and makes your project more portable.
You can create a virtual environment using Python's built-in venv module. First, navigate to your project's folder in your terminal. Then, run the following commands.
# Create a virtual environment named 'venv'
python -m venv venv
# Activate it on macOS or Linux
source venv/bin/activate
# Or, activate it on Windows
venv\Scripts\activate
Once your virtual environment is active, your terminal prompt will usually change to show the environment's name. Now you can install Flask using pip, Python's package installer.
pip install Flask
That's it! Flask is now installed and ready to use in your project.
Your First Flask App
Let's create the classic "Hello, World!" application. Create a new file named app.py and add the following code.
from flask import Flask
# 1. Create an instance of the Flask app
app = Flask(__name__)
# 2. Define a route and its corresponding function
@app.route('/')
def hello_world():
return 'Hello, World!'
# 3. A conditional to run the app
if __name__ == '__main__':
app.run(debug=True)
Let's break this down:
- We import the
Flaskclass and create an instance of it calledapp. The__name__argument helps Flask know where to find other files like templates, which we'll cover later. @app.route('/')is a decorator. It's a special Python feature that modifies the function right below it. This line tells Flask that when someone visits the main URL of our site (the/path), it should run thehello_world()function.- The
if __name__ == '__main__':line is standard Python. It ensures that the development server only runs when the script is executed directly, not when it's imported into another file.app.run(debug=True)starts the server. Thedebug=Truepart is useful during development because it automatically reloads the server when you change your code and provides helpful error messages.
To see it in action, save the file and run it from your terminal.
python app.py
You should see some output telling you that the server is running. Open your web browser and go to the address it provides, usually http://127.0.0.1:5000. You'll see "Hello, World!" on the page.
Routing and Requests
The core of any web application is handling requests. A user types a URL into their browser (making a request), and the server sends back a response. The @app.route() decorator is Flask's way of connecting a specific URL path to the Python function that generates the response.
This function is called a view function. In our example, hello_world() is the view function for the / route.
You can create as many routes as you need. Let's add another one to our app.py file.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
# A new route
@app.route('/about')
def about_page():
return 'This is the about page.'
If you save the file and your server is still running in debug mode, it will automatically reload. Now you can visit http://127.0.0.1:5000/about in your browser to see the new message.
Flask's routing can also capture parts of the URL as variables. This is useful for creating dynamic pages, like user profiles or blog posts. You define a variable in the route by putting it in angle brackets, like <variable_name>.
# A route with a dynamic part
@app.route('/user/<username>')
def show_user_profile(username):
return f'Hello, {username}!'
# You can also specify a type
@app.route('/post/<int:post_id>')
def show_post(post_id):
# post_id is now an integer
return f'Post Number: {post_id}'
In the first new route, visiting /user/Alice will display "Hello, Alice!". The value from the URL is passed as an argument to the view function.
In the second, we specified that post_id should be an integer (int:). Now, if you visit /post/123, it will work. But if you try /post/abc, Flask will automatically return a "Not Found" error because "abc" isn't an integer. This simple system is the foundation for building complex and interactive web applications.
Ready to check your understanding of these basic concepts?
What is the primary characteristic of Flask that distinguishes it as a 'micro' framework?
Why is it considered a best practice to use a virtual environment when developing a Flask application?
You've now set up a Flask environment and built a simple web application. You've seen how to map URLs to Python functions to handle requests, which is the fundamental building block for any web service.
