Web Development with Python
Section 6: Web Development with Python
Lesson 1: Introduction to Flask Framework
1.1 Setting Up a Basic Flask Application
Flask is a lightweight web application framework for Python. To get started, you need to install Flask and set up a basic application.
Example:
# Setting up a basic Flask application
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, Flask!'
if __name__ == '__main__':
app.run(debug=True)
1.2 Creating Routes and Templates
Flask uses routes to map URLs to functions, and templates to render dynamic content.
Example:
# Creating routes and templates
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html', title='Home', content='Welcome to my Flask app!')
@app.route('/about')
def about():
return render_template('about.html', title='About')
if __name__ == '__main__':
app.run(debug=True)
HTML templates (index.html and about.html) should be placed in a folder named templates in the same directory as your Flask application.
Lesson 2: Interacting with Databases
2.1 Using SQLite or Other Databases with Flask
Flask supports various databases, and SQLite is a popular choice for small to medium-sized applications.
Example:
# Interacting with databases (using SQLite)
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
@app.route('/')
def home():
users = User.query.all()
return render_template('users.html', title='Users', users=users)
if __name__ == '__main__':
app.run(debug=True)
In this example, the SQLAlchemy extension is used to interact with an SQLite database. The User class represents a table in the database. The home route queries all users from the database and renders the users.html template.
In Section 6, we introduced web development with Python using the Flask framework. Flask provides a simple and flexible way to build web applications.
We covered the basics of setting up a Flask application, creating routes to handle different URLs, and using templates to render dynamic content. Additionally, we explored how to interact with databases, with a focus on SQLite and the SQLAlchemy extension.
As you delve deeper into web development with Flask, you can expand your skills by incorporating more advanced features, implementing user authentication, and deploying your applications to production servers. Flask's modular design and extensive documentation make it an excellent choice for both beginners and experienced developers in the web development space.