When a web application built with Flask needs persistent data storage, MySQL is the most logical choice. Unlike PHP, where the connection is often established directly, Python typically utilizes libraries like mysql-connector-python.
1. Installing Required Tools
Before starting, we must install the MySQL driver for Python. This is done with a simple terminal command:
pip install mysql-connector-python flask
2. Code Example for Reading from the Database
The following example demonstrates how Flask opens a database connection, retrieves data, and prepares it for processing:
import mysql.connector
from flask import Flask
app = Flask(name)
def get_data():
db = mysql.connector.connect(
host="localhost",
user="user",
password="password",
database="my_blog"
)
cursor = db.cursor(dictionary=True)
cursor.execute("SELECT title, content FROM posts")
results = cursor.fetchall()
db.close()
return results
@app.route("/blog")
def show_blog():
posts = get_data()
# Data would be sent to an HTML template here
return f"Number of posts in database: {len(posts)}"
if name == "main":
app.run(debug=True)
3. Advantages of Using Python for the Backend
- Data Processing: Python allows the use of libraries like Pandas for advanced statistics on database entries.
- Automation: Easily create scripts that check the database at specific times and send reports.
- Security: Flask supports ORM tools (like SQLAlchemy) that provide additional protection against attacks.
Using Python on the web doesn't mean giving up classic HTML. Flask allows us to maintain total control over the visual part, while Python handles the logic in the background.