In the world of web development, Flask has emerged as a lightweight and easy-to-use Python web framework for building scalable web applications. With its simplicity and flexibility, Flask allows you to develop a web app with minimal setup. If you’re new to web development or Flask, this guide will help you build your first web app in under an hour.
What You’ll Need
Before we start, make sure you have Python installed on your computer. Flask can be installed using pip, Python’s package installer. If you haven’t installed Flask yet, you can do so by running the following command in your terminal:
pip install Flask
Setting Up Your Project
First, create a new directory for your project and navigate into it:
mkdir flask_app && cd flask_app
Inside this directory, create a new Python file named app.py
. This file will contain the code for your Flask application.
Your First Flask App
Open app.py
in your favorite text editor 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)
This code snippet does the following:
- Imports the Flask class.
- Creates an instance of the Flask class.
- Defines a route
/
that points to thehome
function, which returns the string ‘Hello, Flask!’ when visited. - Finally, runs the app in debug mode, which helps in automatically reloading your app with any changes you make during development.
Running Your App
Save app.py
and return to your terminal. Run your application using the command:
python app.py
You should see output indicating that the server is running, typically on http://127.0.0.1:5000/
. Open this URL in your web browser, and you should be greeted with “Hello, Flask!”
Expanding Your Application
Let’s add another page to your application. In app.py
, add a new route and function as follows:
@app.route('/about')
def about():
return 'This is a simple Flask web app.'
Restart your Flask server (if it’s not running in debug mode), and navigate to http://127.0.0.1:5000/about
in your browser. You’ll now see the message “This is a simple Flask web app.”
Conclusion
Congratulations! You’ve just created a basic web application using Flask. This guide introduced you to setting up Flask, creating a simple web app, and running it locally. Flask’s simplicity and extensibility make it an excellent choice for beginners and experienced developers alike. To further your knowledge, explore Flask’s documentation to learn about templates, form handling, and database integration. Happy coding!