This tutorial aims to guide you through the process of creating a basic Flask project and running it on your local machine. You will learn the structure of a Flask application, including how to create views and routes.
By the end of this tutorial, you will have a working Flask application that you can use as a starting point for your projects.
Prerequisites:
- Basic knowledge of Python
- Python and pip installed on your machine
- A text editor or IDE installed
Flask is a micro web framework written in Python. It's called a micro framework because it doesn't require particular tools or libraries, yet it's flexible and supports extensions that give additional functionality like form validation, upload handling, various open authentication technologies, and more.
Firstly, we need to install Flask. Open your terminal and run the following command:
pip install flask
Now that Flask is installed, let's create a basic Flask application. Create a new file named app.py
and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, Flask!'
if __name__ == '__main__':
app.run(debug=True)
In this code, we first import the Flask class. An instance of this class is our WSGI application.
The @app.route('/')
decorator creates a route for the function home()
. When you visit the root URL of your application (http://localhost:5000/), Flask triggers this function and returns its result to the browser.
The if __name__ == '__main__'
block ensures the server only runs if the script is executed directly from the Python interpreter and not used as an imported module.
Let's add a new route to our application.
@app.route('/about')
def about():
return 'About page'
With this new route, when you visit http://localhost:5000/about, you'll see the text "About page".
In this tutorial, you've learned how to create a Flask project, define routes and views, and run your application. Your next steps could be learning how to serve static files, handle form submissions, or use a database with Flask.
Additional resources:
- Flask Documentation
- The Flask Mega-Tutorial
Solution:
@app.route('/hello/<name>')
def hello(name):
return 'Hello, {}!'.format(name)
In this solution, we're using a dynamic route. The <name>
part of the route will be passed as a parameter to the hello()
function.
Solution:
@app.route('/sum/<int:num1>/<int:num2>')
def sum(num1, num2):
return str(num1 + num2)
In this solution, we're using dynamic routes to capture two numbers from the URL. We specify the type of the parameters with <int:num1>
and <int:num2>
. The sum()
function adds these numbers and returns the result. We convert the result to a string because a route function in Flask should return a string, a response instance, or a valid WSGI application.
For further practice, try creating more complex routes, or start working with HTML templates and forms.