preface

This article uses The Python Web framework Django to connect and operate the MySQL database student information Management system (SMS). It mainly includes the function of adding, deleting, changing and checking student information, aiming to get a quick start in Python Web. The end of the article has the source address of the whole project. No more words to see the effect:

The development environment

  • Development tool: Pycharm 2020.1
  • Development language: Python 3.8.0
  • Web Framework: Django 3.0.6
  • Database: MySQL5.7
  • Operating system: Windows 10

The project of actual combat

1. Create a project (SMS)

File->New Project->Django

Wait a moment, the directory structure of the project is shown below

Verify that Django and mysqlClient interpreters are installed after the project is created. file->Settings

If no, run the following command on the Terminal to complete the installation

pip install django
pip install mysqlclient
Copy the code

If PIP install fails to Read time out, please set the timeout duration to be extended. The default value is 15s

pip --default-timeout=180 install -U django
pip --default-timeout=180 install -U mysqlclient
Copy the code

The -u parameter is short for –upgrade to upgrade the installed package to the latest version

2. Create SIMS

Open Pycharm’s Terminal and enter the following command to create the SIMS application

python manage.py startapp sims
Copy the code

After the application is created, add smis under INSTALLED_APPS in the settings.py file of the project to register the application

3. Django configuration MySQL

Create SMS database in local MySQL, change project Settings connection information from default SQLite to MySQL

DATABASES = {
     'default': {
        'ENGINE': 'django.db.backends.mysql'.'NAME':  'sms'.'USER': 'root'.'PASSWORD': '123456'.'HOST': '127.0.0.1'.'PORT': 3306}}Copy the code

To test the connection, click Database->+->Data Source->MySQL at the top right of Pycharm

Download the connection driver and configure database connection information

Click Test Connection to Test the Connection. Click OK to display the following structure information, indicating that the local MySQL Connection is successful

4. Data Model creation (M)

Add the Student model under the application SIMS models.py

class Student(models.Model) :
    student_no = models.CharField(max_length=32, unique=True)
    student_name = models.CharField(max_length=32)
Copy the code

5. Data model migration

Terminal Enter the following two commands. The first command generates a file to record model changes. The second is to synchronize model changes to the database, where we can generate the corresponding table structure.

python manage.py makemigrations sims

python manage.py migrate sims
Copy the code

The generated data table structure is shown below

6. Configure routes

It is essential to understand the mapping configuration of the request path URL and processing method, starting by adding the routing configuration of the SIMS in the urls.py file of the project SMS

from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^sims/', include('sims.urls')))Copy the code

Then add a file named urls.py to the SIMS and add the routing configuration as follows

# coding=utf-8
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index),
    url(r'^add/$', views.add),
    url(r'^edit/$', views.edit),
    url(r'^delete/$', views.delete)
]
Copy the code

7. Processing function (V)

In the view layer file views.py of SIMS, the processing function of adding, deleting, modifying and checking student information was added. I used native SQL here to facilitate the in-depth understanding of its execution process. I will add the Django framework’s database manipulation methods to Github sometime later.

import MySQLdb
from django.shortcuts import render, redirect


# Create your views here.
Student information list processing function
def index(request) :
    conn = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="sms", charset='utf8')
    with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
        cursor.execute("SELECT id,student_no,student_name FROM sims_student")
        students = cursor.fetchall()
    return render(request, 'student/index.html', {'students': students})

# New student information processing function
def add(request) :
    if request.method == 'GET':
        return render(request, 'student/add.html')
    else:
        student_no = request.POST.get('student_no'.' ')
        student_name = request.POST.get('student_name'.' ')
        conn = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="sms", charset='utf8')
        with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
            cursor.execute("INSERT INTO sims_student (student_no,student_name) "
                           "values (%s,%s)", [student_no, student_name])
            conn.commit()
        return redirect('.. / ')

# student information modification processing function
def edit(request) :
    if request.method == 'GET':
        id = request.GET.get("id")
        conn = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="sms", charset='utf8')
        with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
            cursor.execute("SELECT id,student_no,student_name FROM sims_student where id =%s"[id])
            student = cursor.fetchone()
        return render(request, 'student/edit.html', {'student': student})
    else:
        id = request.POST.get("id")
        student_no = request.POST.get('student_no'.' ')
        student_name = request.POST.get('student_name'.' ')
        conn = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="sms", charset='utf8')
        with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
            cursor.execute("UPDATE sims_student set student_no=%s,student_name=%s where id =%s",
                           [student_no, student_name, id])
            conn.commit()
        return redirect('.. / ')

Student information delete processing function
def delete(request) :
    id = request.GET.get("id")
    conn = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="sms", charset='utf8')
    with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
        cursor.execute("DELETE FROM sims_student WHERE id =%s"[id])
        conn.commit()
    return  redirect('.. / ')
Copy the code

8. Template Page (T)

  • Student information list page
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student list</title>
</head>
<body>
<table border="1px" width="100%" style="border-collapse: collapse;">
    <a href=".. /sims/add">Add the student</a>
    <tr>
        <th>Serial number</th>
        <th>The name</th>
        <th>Student id</th>
        <th>operation</th>
    </tr>
    {% for student in students %}
        <tr>
            <td align="center">{{ forloop.counter }} </td>
            <td align="center">{{ student.student_name }} </td>
            <td align="center">{{ student.student_no }} </td>
            <td align="center">
                <a href=".. /sims/edit/? id={{ student.id }}">The editor</a>
                <a href=".. /sims/delete/? id={{ student.id }}">delete</a>
            </td>
        </tr>
    {% endfor %}
</table>
</body>
</html>
Copy the code
  • New page for student information
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Students add</title>
    <style>
        form {
            margin: 20px auto;
            width: 500px;
            border: 1px solid #ccc;
            padding: 20px
        }
    </style>
</head>
<body>
<form method="post" action=".. /add/">
    {% csrf_token %}
    <table>
        <tr>
            <th>The name</th>
            <td><input name="student_name"></td>
        </tr>
        <tr>
            <th>Student id</th>
            <td><input name="student_no"/></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit"/>
            </td>
        </tr>
    </table>
</form>
</body>
</html>
Copy the code
  • Student information edit page
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Students to edit</title>
    <style>
        form {
            margin: 20px auto;
            width: 500px;
            border: 1px solid #ccc;
            padding: 20px
        }
    </style>
</head>
<body>
<form method="post" action=".. /edit/">
    {% csrf_token %}
    <input type="hidden" name="id" value="{{ student.id }}"/>
    <table>
        <tr>
            <th>The name</th>
            <td><input name="student_name" value="{{ student.student_name }}"></td>
        </tr>
        <tr>
            <th>Student id</th>
            <td><input name="student_no" value="{{ student.student_no }}"/></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit"/>
            </td>
        </tr>
    </table>
</form>
</body>
</html>
Copy the code

9. Start the Web service test

Terminal Run the following command to start the Web service

python manage.py runserver
Copy the code

Service starts, open a browser enter http://127.0.0.1:8000/sims/ can enter the students information management list page

conclusion

At this point, based on Python+Django+MySQL environment to build a Python Web with add, delete, change and query functions are complete. Hopefully this will really help you get started with Python Web development. If you have any problems in the process of building, welcome to leave a message below, I will immediately reply to see! If you can give a attention oh, thank you!

The appendix

Finally attached to the project the entire source github repository address github.com/hxrui/pytho… Welcome star to exchange and study.