In this tutorial, we will learn how to create a simple web application with Flask. Flask is a micro web framework written in Python, which means it does not require particular tools or libraries. It has a small and easy-to-extend core. It’s a microframework that doesn’t include an ORM (Object Relational Manager) or such features.
You will learn:
- How to set up a Flask environment
- How to create a simple Flask application
- Understand the basic principles of Flask
Prerequisites:
- Basic knowledge of Python programming language
- Python installed on your machine (Python 3 recommended)
Before we begin, we need to install Flask. Open your terminal and type:
pip install flask
Now, let's create a new file named "app.py" and write our first Flask web app:
# Importing flask module in the project is mandatory
# An object of Flask class is our WSGI application.
from flask import Flask
# Flask constructor takes the name of
# current module (__name__) as argument.
app = Flask(__name__)
# The route() function of the Flask class is a decorator,
# which tells the application which URL should call
# the associated function.
@app.route('/')
# ‘/’ URL is bound with welcome() function.
def welcome():
return "Welcome to Flask!"
# main driver function
if __name__ == '__main__':
# run() method of Flask class runs the application
# on the local development server.
app.run()
Save the file and in the terminal, navigate to the directory containing the file you just created and run the app using the command:
python app.py
You will see output telling you that the server is running. Open a web browser and navigate to http://127.0.0.1:5000/
to see your application.
Let's create a new route in our application:
@app.route('/hello/<name>')
def hello_name(name):
return 'Hello %s!' % name
In this example, '/' URL is bound to the 'hello_name()' function. As a result, if we navigate to http://127.0.0.1:5000/hello/John
, 'Hello John!' will be rendered in the web browser.
In this tutorial, we learned how to set up a Flask environment, create a simple Flask application, and create routes in the application.
Next steps for learning include exploring how to use templates in Flask to create more complex web pages, and learning about how to handle form data and create RESTful web services with Flask.
Additional resources:
- The Flask Documentation (http://flask.palletsprojects.com/en/1.1.x/)
- Flask Web Development with Python Tutorial (https://www.tutorialspoint.com/flask)
Solutions:
@app.route('/add/<int:num1>/<int:num2>')
def add(num1, num2):
return str(num1 + num2)
@app.route('/home')
def home():
return '''
<html>
<body>
<h1>Welcome to My Home Page!</h1>
</body>
</html>
'''
@app.route('/reverse/<string>')
def reverse(string):
return string[::-1]
Remember, the best way to learn Flask is by practice. Try to create your own web application using what you've learned in this tutorial.