Welcome back to another exciting day in our PythonForDevOps series. Today, we're delving into the world of web applications with Python using Flask. If you've been following along, you know we've covered a lot, but buckle up because today is where things get interactive.
Flask: What's in the Flask?
Flask is a micro web framework written in Python. Now, don't let the term "micro" fool you; Flask may be lightweight, but it packs a punch when it comes to building web applications. It's like having a powerful tool in a compact package.
Installation
Before we jump into the coding arena, let's make sure Flask is ready to roll. Open up your terminal and run:
pip install Flask
With Flask installed, we're good to go.
Hello Flask!
Our journey begins with the classic "Hello, World!" example. Creating a Flask application is as simple as:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, Flask!'
Let's break this down:
We import the Flask class from the Flask module.
We create an instance of the Flask class, usually named app.
The @app.route('/') decorator tells Flask that the hello function should be executed when someone visits the root URL ('/').
The hello function returns the string 'Hello, Flask!'.
Save your script and run it. Open your browser and go to http://localhost:5000/, and voila! You've just served your first Flask application.
Routing for Success
Flask's routing system allows you to define the behavior of your app based on the URL requested. Let's create a simple example with multiple routes:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Welcome to the Home Page!'
@app.route('/about')
def about():
return 'Learn more about us on the About Page.'
@app.route('/contact')
def contact():
return 'Contact us at contact@example.com.'
Now, visiting /about or /contact will display different content. Routing in Flask is like giving directions to your app, telling it where to go based on user input.
Templates: Dressing up Your Pages
Hardcoding HTML in your Python script isn't ideal. Flask makes it easy to separate your code and presentation using templates. Create a folder named templates in your project directory and add an HTML file, let's call it index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }}</title>
</head>
<body>
<h1>{{ content }}</h1>
</body>
</html>
Now, update your Flask app:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html', title='Home Page', content='Welcome!')
@app.route('/about')
def about():
return render_template('index.html', title='About Page', content='Learn more about us.')
@app.route('/contact')
def contact():
return render_template('index.html', title='Contact Page', content='Get in touch!')
This way, your HTML and Python code are neatly separated, making it easier to maintain and understand.
Forms: Getting User Input
Web applications often require user input. Flask makes it simple to handle forms. Let's create a basic form to get a user's name:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/form', methods=['GET', 'POST'])
def form():
if request.method == 'POST':
name = request.form['name']
return f'Thank you, {name}!'
return render_template('form.html')
In your templates folder, create a file named form.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Page</title>
</head>
<body>
<form method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
Now, visiting /form will display a form. When submitted, it will thank the user by name. Flask takes care of handling the form data effortlessly.
Congratulations! You've taken your first steps into the world of web development with Flask. We've covered the basics of routing, templates, and forms, laying a solid foundation for building more complex applications.
Thank you for reading!
*** Explore | Share | Grow ***
Comments