In the world of web development, Python’s Flask framework stands out for its simplicity and elegance. It’s a micro web framework, meaning it’s lightweight and easy to use, perfect for getting a web application up and running quickly. This article is a beginner’s guide to building a basic web application using Flask. We’ll cover setting up Flask, creating a simple web page, and adding some interactivity.
What is Flask?
Flask is a web framework for Python, which provides tools, libraries, and technologies that allow you to build a web application. It is classified as a microframework because it requires little to no dependencies to get started, making it ideal for small to medium-sized web applications.
Setting Up Flask
First, you’ll need to have Python installed on your machine. Then, you can install Flask using pip:
pip install Flask
Creating a Flask App
Once Flask is installed, you can start by creating a new Python file for your app, let’s say app.py. In this file, import Flask and create an instance of the Flask class.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
In this simple application, we:
- Import the
Flaskclass. - Create an instance of the class.
__name__is a Python special variable that gets set to the name of the module in which it is used. - Use the
route()decorator to tell Flask what URL should trigger our function. - Define a function,
hello_world, which returns the string ‘Hello, World!’. - Run the application with
app.run(). Settingdebug=Trueallows possible Python errors to appear on the web page.
Running the App
To run the app, simply go to your terminal, navigate to the folder where your app.py is located, and type:
python app.py
You’ll see output that tells you the server is running. By default, Flask runs on http://127.0.0.1:5000/. Open this URL in your web browser, and you should see “Hello, World!” displayed.
Creating More Views
You can create more views by adding more functions and decorators. Let’s add a new page:
@app.route('/about')
def about():
return 'About page'
This creates a new view at http://127.0.0.1:5000/about that displays “About page”.
Templates
For anything beyond a simple project, you’ll want to use templates. Templates separate the business logic from the presentation logic. Flask uses Jinja2 as its template engine.
First, create a folder named templates in your project directory. Then, create an HTML file inside this folder, let’s say index.html:
<!doctype html>
<html>
<head>
<title>Hello from Flask</title>
</head>
<body>
<h1>{{ message }}</h1>
</body>
</html>
You can render this template using the render_template function:
from flask import render_template
@app.route('/')
def home():
return render_template('index.html', message="Hello from Flask")
This will pass the message “Hello from Flask” to the index.html template and display it inside the <h1> tag.
Adding Interactivity with Forms
Flask can also handle user input using forms. First, install Flask-WTF:
pip install Flask-WTF
Create a form in a new HTML file, form.html:
<form method="post" action="/submit">
<input type="text" name="name" placeholder="Enter your name"/>
<input type="submit" value="Submit"/>
</form>
Handle form submission in app.py:
from flask import request
@app.route('/form')
def form():
return render_template('form.html')
@app.route('/submit', methods=['POST'])
def submit():
name = request.form['name']
return f'Hello {name}'
Now, when you go to http://127.0.0.1:5000/form, you can enter your name, submit the form, and be greeted personally.
Conclusion
Flask is an incredibly versatile and beginner-friendly framework for web development in Python. It allows for the quick creation of web applications with minimal setup and a clear, understandable syntax. Whether you’re building a small project or a large web application, Flask provides you with all the necessary tools to bring your project to life. The real beauty of Flask lies in its simplicity and the power it offers to Python developers to create feature-rich web applications. As you continue to explore Flask, you’ll discover more of its functionalities and how it can be used in conjunction with other tools and technologies to create more complex and robust web applications.