This tutorial will guide you through the installation process of Flask on different operating systems: Windows, macOS, and Linux. Flask is a popular micro web framework written in Python, widely used for developing web applications.
By the end of this tutorial, you will learn:
Prerequisites: Basic knowledge of Python is recommended. Python should be installed on your system. If Python is not installed, you can download it from the official Python website.
We will use pip, the Python package installer. If pip is not installed, you can download it from the pip official website.
pip install virtualenv
virtualenv flask_env
flask_env\Scripts\activate
pip install Flask
pip3 install virtualenv
virtualenv flask_env
source flask_env/bin/activate
pip3 install Flask
pip3 install virtualenv
virtualenv flask_env
source flask_env/bin/activate
pip3 install Flask
Tip: Using a virtual environment is a best practice to keep the dependencies required by different projects separate.
Now that Flask is installed, let's create a basic web application.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask
: This line imports the Flask module and creates a web server from the Flask web server class.app = Flask(__name__)
: An instance of class Flask is our WSGI application.@app.route('/')
: The @app.route
decorator in Flask is used to bind URL to a function.def home():
: This function will be run when the home URL ('/') is visited.return "Hello, Flask!"
: The string "Hello, Flask!" is returned on visiting the home URL.if __name__ == '__main__':
: This line ensures the server only runs if the script is directly run, and not imported.app.run(debug=True)
: This line will run the application instance. The debug=True
allows possible Python errors to appear on the web page.Expected output on visiting localhost:5000
: "Hello, Flask!"
In this tutorial, you learned how to install Flask on Windows, macOS, and Linux. We also created a basic Flask web application.
Next steps for learning could include exploring more Flask functionalities, such as URL building, HTTP methods, templates, static files, and request data.
Additional resources:
1. Flask Documentation
2. The Flask Mega-Tutorial
Solution:
python
@app.route('/about')
def about():
return "About Page"
This will display "About Page" when you visit localhost:5000/about
.
Solution:
python
@app.route('/user/<username>')
def user(username):
return "User: " + username
This will display "User: your_username" when you visit localhost:5000/user/your_username
.
For further practice, try to extend your Flask application by adding more routes and different functionalities.