Lesson No 25 Python Typecasting Essentials for Beginners
Introduction
In this comprehensive tutorial, we will walk through the process of building a web application using the Python Flask framework. Flask is a lightweight and flexible web framework that makes it easy to create dynamic websites and web applications. We'll cover everything from setting up the development environment to building a complete web application with a database backend.
Getting Started
To begin, we'll need to set up our development environment. First, we'll install Flask and the necessary dependencies. Then, we'll create a simple "Hello, World!" web page to ensure our setup is working correctly.
Installing Flask
Flask can be installed using pip, the Python package manager. Open your terminal or command prompt and run the following command:
pip install flask
This will install the latest version of Flask on your system.
Creating a Basic Web Page
Next, we'll create a simple web page using Flask. Create a new file called app.py
and add the following code:
from flask import Flask
app = Flask(__name__)@app.route('/')def index():return 'Hello, World!'if __name__ == '__main__':app.run()
This code sets up a basic Flask application with a single route that displays the message "Hello, World!" when the root URL (/
) is accessed.
To run the application, save the file and execute the following command in your terminal:
python app.py
You should see output indicating that the server is running. Open your web browser and navigate to http://localhost:5000
to see the "Hello, World!" message.
Proper Coding with Flask
Now that we have a basic web page up and running, let's explore some more advanced features of Flask. We'll learn how to use templates, handle different routes, and interact with a database.
Using Templates
Flask uses the Jinja2 templating engine to make it easy to create dynamic web pages. Templates allow you to separate the presentation logic from the application logic, making your code more modular and maintainable.
Create a new folder called templates
in the same directory as your app.py
file. Inside the templates
folder, create a new file called index.html
and add the following HTML code:
<!DOCTYPE html>
<html><head><title>My Flask App</title></head><body><h1>Welcome to my Flask app!</h1><p>This is a dynamic web page created using Flask and Jinja2.</p></body></html>
Now, update the app.py
file to use the template:
from flask import Flask, render_template
app = Flask(__name__)@app.route('/')def index():return render_template('index.html')
The render_template()
function is used to render the index.html
template and return the resulting HTML to the client.
Working with Routes
Flask uses the concept of routes to map URLs to Python functions. Let's explore different types of routes and how to handle them.
Static Routes
Static routes are the most basic type of route, where a specific URL maps to a specific function. For example, we can add a new route for an "About" page:
@app.route('/about')
def about():return render_template('about.html')
This will create a new route at /about
that will render the about.html
template.
Dynamic Routes
Dynamic routes allow you to create routes that can accept parameters. For example, we can create a route that displays a user's profile based on their username:
@app.route('/user/')
def user_profile(username):return f'Welcome to {username}\'s profile page.'
In this example, the <username>
part of the URL is a placeholder that will be captured as a parameter and passed to the user_profile()
function.
Template Inheritance
Template inheritance allows you to create a base template that other templates can extend. This helps to maintain a consistent look and feel across your application.
Create a new file called base.html
in the templates
folder and add the following code:
<!DOCTYPE html>
<html><head><title>{% block title %}{% endblock %}</title></head><body>{% block content %}{% endblock %}</body></html>
Now, update the index.html
file to extend the base.html
template:
{% extends 'base.html' %}
{% block title %}Home{% endblock %}{% block content %}<h1>Welcome to my Flask app!</h1><p>This is a dynamic web page created using Flask and Jinja2.</p>{% endblock %}
By using template inheritance, you can easily maintain a consistent layout and design across your entire application.
Working with Databases
Most web applications require some form of data storage, such as a database. Flask does not come with a built-in database layer, but it can be easily integrated with various database systems, such as SQLite, MySQL, or PostgreSQL.
CRUD Operations with SQLite
In this example, we'll use SQLite, a lightweight, file-based database, to demonstrate how to perform CRUD (Create, Read, Update, Delete) operations.
First, we need to install the Flask-SQLAlchemy extension, which provides a simple way to interact with databases using SQLAlchemy, a popular Python SQL toolkit:
pip install flask-sqlalchemy
Next, update the app.py
file to set up the database connection and define a simple model:
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemyapp = Flask(__name__)app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'db = SQLAlchemy(app)class User(db.Model):id = db.Column(db.Integer, primary_key=True)name = db.Column(db.String(80), nullable=False)email = db.Column(db.String(120), unique=True, nullable=False)def __repr__(self):return f''
Now, we can add routes to handle CRUD operations:
@app.route('/users/create', methods=['GET', 'POST'])
def create_user():if request.method == 'POST':name = request.form['name']email = request.form['email']user = User(name=name, email=email)db.session.add(user)db.session.commit()return 'User created successfully!'return render_template('create_user.html')@app.route('/users')def list_users():users = User.query.all()return render_template('users.html', users=users)@app.route('/users//delete', methods=['POST'])def delete_user(user_id):user = User.query.get(user_id)db.session.delete(user)db.session.commit()return 'User deleted successfully!'
These routes allow users to create new users, view a list of all users, and delete users from the database.
Conclusion
In this tutorial, you've learned how to build a web application using the Python Flask framework. You've covered topics such as setting up the development environment, creating basic web pages, using templates, working with routes, and integrating a database. With this knowledge, you can now start building your own web applications using Flask.
No comments:
Post a Comment