Python Web實戰:Python+Django+MySQL實現基於Web版的增刪改查

你好,舊時光發表於2020-05-10

前言

本篇使用Python Web框架Django連線和操作MySQL資料庫學生資訊管理系統(SMS),主要包含對學生資訊增刪改查功能,旨在快速入門Python Web,少走彎路。效果演示在專案實戰最後一節,文章結尾有整個專案的原始碼地址。

開發環境

  • 開發工具:Pycharm 2020.1
  • 開發語言:Python 3.8.0
  • Web框架:Django 3.0.6
  • 資料庫:MySQL5.7
  • 作業系統:Windows 10

專案實戰

1. 建立專案(學生管理系統-sms)

File->New Project->Django

稍等片刻,專案的目錄結構如下圖

專案建立後確認是否已安裝Django和mysqlclient直譯器,如何確認?file->Settings

如果沒有請在Terminal終端輸入以下命令完成安裝

pip install django
pip install mysqlclient

如果在執行pip install 報錯Read time out請設定延長下超時時間,預設15s,網路不好情況下很易超時

pip --default-timeout=180 install -U django
pip --default-timeout=180 install -U mysqlclient

引數-U是--upgrade簡寫,把安裝的包升級到最新版本

2. 建立應用(學生資訊管理系統-sims)

開啟Pycharm的Terminal終端,輸入以下命令建立sims應用

python manage.py startapp sims

應用建立後要在專案的settings.py檔案裡的INSTALLED_APPS下面新增smis完成應用註冊

3. 配置MySQL資料庫

在本地MySQL建立sms資料庫,修改專案的settings連線資訊由預設的sqlite修改為MySQL

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

測試連線,依次點選Pycharm右上角的Database->+->Data Source->MySQL

下載連線驅動和配置資料庫連線資訊

點選Test Connection測試連線,連線通過點選OK出現如下的結構資訊表示連線本地MySQL成功

4.資料模型建立(M)

在應用sims下models.py新增Student模型

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

5.資料模型遷移

Terminal終端輸入以下兩條命令,其作用第一條生成檔案記錄模型的變化;第二條是將模型變化同步至資料庫,我們可以在資料庫生成對應的表結構。

python manage.py makemigrations sims

python manage.py migrate sims

生成資料表結構如下所示

6.路由配置

本質可以理解請求路徑url和處理方法的對映配置,首先在專案sms的urls.py檔案中新增sims的路由配置

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'))
]

然後在sms新增一個名為urls.py的檔案,新增路由配置如下

# 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)
]

7.處理函式新增(V)

在應用sims的檢視層檔案views.py新增對應學生資訊增刪改查的處理函式,這裡我使用的原生SQL,便於深入理解其執行過程。後面有時間我會在github上新增Django框架提供的運算元據庫方式。

import MySQLdb
from django.shortcuts import render, redirect


# Create your views here.
# 學生資訊列表處理函式
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})

# 學生資訊新增處理函式
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('../')

# 學生資訊修改處理函式
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('../')

# 學生資訊刪除處理函式
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('../')

8.模板頁面建立(T)

  • 學生資訊列表頁
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>學生列表</title>
</head>
<body>
<table border="1px" width="100%" style="border-collapse: collapse;">
    <a href="../sims/add">新增學生</a>
    <tr>
        <th>編號</th>
        <th>姓名</th>
        <th>學號</th>
        <th>操作</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 }}">
                    編輯
                </a>
                <a href="../sims/delete/?id={{ student.id }}">
                    刪除
                </a>
            </td>
        </tr>
    {% endfor %}
</table>
</body>
</html>
  • 學生資訊新增頁
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>學生新增</title>
    <style>
        form {
            margin20px auto;
            width500px;
            border1px solid #ccc;
            padding20px
        }
    
</style>
</head>
<body>
<form method="post" action="../add/">
    {% csrf_token %}
    <table>
        <tr>
            <th>姓名</th>
            <td><input name="student_name"></td>
        </tr>
        <tr>
            <th>學號</th>
            <td><input name="student_no"/></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit"/>
            </td>
        </tr>
    </table>
</form>
</body>
</html>
  • 學生資訊編輯頁
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>學生編輯</title>
    <style>
        form {
            margin20px auto;
            width500px;
            border1px solid #ccc;
            padding20px
        }
    
</style>
</head>
<body>
<form method="post" action="../edit/">
    {% csrf_token %}
    <input type="hidden" name="id" value="{{ student.id }}"/>
    <table>
        <tr>
            <th>姓名</th>
            <td><input name="student_name" value="{{ student.student_name }}"></td>
        </tr>
        <tr>
            <th>學號</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>

9.啟動web服務測試

Terminal終端輸入以下命令啟動web服務

python manage.py runserver
image
image

服務啟動後,開啟瀏覽器輸入http://127.0.0.1:8000/sims/即可進入學生資訊管理列表頁

10.功能演示

最後最重要的事情,看效果。我這裡簡單演示下,話不多說,看動態圖

結語

至此,基於Python+Django+MySQL環境搭建一個擁有增刪改查功能的Python Web就完成了。希望能夠真正幫到大家快速入門Python Web開發。如果在搭建過程中您有遇到什麼問題,歡迎在下方留言,看到我會立即回覆的!可以的話給個關注哦,謝謝您!

附錄

最後附上專案整個原始碼的github倉庫地址 https://github.com/hxrui/python-diango-web.git,歡迎star交流學習。

相關文章