杰瑞科技汇

Python、MySQL、Django 如何协同工作?

Of course! This is a very common and powerful combination for building web applications. Let's break down what each component is, how they work together, and walk through a practical example.

Python、MySQL、Django 如何协同工作?-图1
(图片来源网络,侵删)

The Big Picture: A Three-Layered Architecture

Think of your web application as a three-tiered system, and Python, Django, and MySQL each play a distinct role:

Component Role Analogy
Python The Language. The fundamental tool used to write the application's logic. The Blueprint. It defines the rules and structure of your house.
Django The Web Framework. A pre-built set of tools and libraries (written in Python) that speeds up development by handling common web tasks. The Construction Kit. It provides the walls, windows, doors, and plumbing so you don't have to build everything from scratch.
MySQL The Database. A system for storing, organizing, and retrieving your application's persistent data (like user info, posts, products). The Foundation & Storage Room. It's where the house is built and where all your belongings (data) are kept safely.

How they connect:

  1. User Request: A user visits your website (e.g., yourwebsite.com/products/).
  2. Django (The Web Server): Django's web server receives the request. It looks at the URL (/products/) and decides which part of your code to run.
  3. Python (The Logic): Django executes your Python code. This code might need to get data from the database.
  4. Django (The ORM): Your Python code doesn't speak SQL directly. Instead, it uses Django's Object-Relational Mapper (ORM). The ORM translates your Python commands into SQL queries.
  5. MySQL (The Database): The SQL query is sent to the MySQL database. MySQL executes the query (e.g., SELECT * FROM products WHERE category = 'electronics';) and sends the results back.
  6. The Journey Back: The data travels back up the chain:
    • MySQL returns the raw data.
    • The ORM converts the data back into Python objects (e.g., a list of Product objects).
    • Your Python code processes these objects, generates an HTML page, and sends it back to the user's browser.

Key Concepts: Django's ORM (The Bridge)

The most important concept for this trio is the ORM. It's what makes interacting with the database so easy in Django. Instead of writing raw SQL like this:

INSERT INTO myapp_author (name, birth_date) VALUES ('J.K. Rowling', '1965-07-31');

You write simple, readable Python like this:

Python、MySQL、Django 如何协同工作?-图2
(图片来源网络,侵删)
# In your Django views.py or models.py
from .models import Author
# Create an author object
author = Author(name="J.K. Rowling", birth_date="1965-07-31")
# Save the object to the database. Django generates and runs the SQL for you!
author.save()

The ORM supports all major database operations (Create, Read, Update, Delete - CRUD) and even handles complex queries, database connections, and security (like preventing SQL injection).


Step-by-Step Guide: Building a Simple To-Do App

Let's build a basic application with a Task model that stores a title and a due date in a MySQL database.

Step 1: Prerequisites

  1. Python: Installed on your system.
  2. MySQL Server: Installed and running. You should know the root password.
  3. Python Virtual Environment: It's a best practice to keep your project's dependencies isolated.
# Create and activate a virtual environment
python -m venv venv
# On Windows:
# venv\Scripts\activate
# On macOS/Linux:
# source venv/bin/activate

Step 2: Install Required Packages

We need Django for the framework and mysqlclient or mysql-connector-python as the database adapter. mysqlclient is very common and performant.

pip install django mysqlclient

Step 3: Create a Django Project and App

# Create a new Django project
django-admin startproject myproject
# Navigate into the project directory
cd myproject
# Create a new app to handle our to-do tasks
python manage.py startapp tasks

Step 4: Configure Django to Use MySQL

  1. Create the MySQL Database: Connect to your MySQL server and create a database for your project.

    Python、MySQL、Django 如何协同工作?-图3
    (图片来源网络,侵删)
    -- Log in to MySQL (e.g., mysql -u root -p)
    CREATE DATABASE myproject_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
  2. Configure settings.py: Open myproject/settings.py and tell Django about your new database.

    # myproject/settings.py
    # ... (other settings)
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',  # The database engine
            'NAME': 'myproject_db',               # The name of the database you created
            'USER': 'root',                       # Your MySQL username
            'PASSWORD': 'your_mysql_password',    # Your MySQL password
            'HOST': '127.0.0.1',                  # Or 'localhost'
            'PORT': '3306',                       # Default MySQL port
            'OPTIONS': {
                'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            },
        }
    }
    # Add your new 'tasks' app to INSTALLED_APPS
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'tasks',  # Add this line
    ]

Step 5: Define the Model (The Database Table)

This is where we define the structure of our Task table in the database. Open tasks/models.py:

# tasks/models.py
from django.db import models
class Task(models.Model):= models.CharField(max_length=200)
    completed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    due_date = models.DateTimeField(null=True, blank=True)
    def __str__(self):
        return self.title

Step 6: Create and Apply Database Migrations

Migrations are Django's way of synchronizing your Python models with the actual database schema.

# This command inspects your models.py files and creates migration files
python manage.py makemigrations
# This command applies the migrations to the database, creating the tables
python manage.py migrate

After running migrate, you will see tables like tasks_task created inside your myproject_db in MySQL.

Step 7: Use the Model in the Admin Panel

Let's make it easy to add tasks through Django's built-in admin interface.

  1. Register the model: Open tasks/admin.py and register your Task model.

    # tasks/admin.py
    from django.contrib import admin
    from .models import Task
    admin.site.register(Task)
  2. Create a superuser: To access the admin panel, you need an admin account.

    python manage.py createsuperuser

    Follow the prompts to create a username, email, and password.

  3. Run the server and test it:

    python manage.py runserver

    Now, open your browser and go to http://127.0.0.1:8000/admin/. Log in with the superuser credentials you just created. You should see a "Tasks" section where you can add, edit, and delete Task objects. When you add one, the data is being saved directly to your MySQL database!


Troubleshooting Common Issues

  • mysqlclient Installation Error: On some systems (especially Windows), mysqlclient can be tricky to install. If pip install mysqlclient fails, you may need to install a MySQL development package first (e.g., mysql-devel on CentOS/RHEL or default-libmysqlclient-dev on Ubuntu) or use mysql-connector-python instead.

    pip install mysql-connector-python

    If you use this, you only need to change one line in settings.py:

    'ENGINE': 'django.db.backends.mysql',
    'OPTIONS': {
        'driver': 'mysql.connector', # Add this line
        # ... other options
    },
  • Access denied for user 'root'@'localhost': Double-check your username and password in settings.py. Make sure the MySQL server is running and that the user has privileges on the database (myproject_db).

  • django.db.utils.OperationalError: (2006, "MySQL server has gone away"): This can happen if a database connection is idle for too long. You can configure Django to close connections after each request in settings.py:

    DATABASES = {
        # ...
        'CONN_MAX_AGE': 0, # Close the database connection after each request
    }
分享:
扫描分享到社交APP
上一篇
下一篇