Python Web实战:Python+Django+MySQL实现基于Web版的增删改查
<h2 id="前言">前言</h2><p>本篇使用Python Web框架Django连接和操作MySQL数据库学生信息管理系统(SMS),主要包含对学生信息增删改查功能,旨在快速入门Python Web,文章结尾有整个项目的源码地址。话不多说先看效果:</p>
<p><img src="https://img-blog.csdnimg.cn/20200510161507425.gif#pic_center" alt="" loading="lazy"></p>
<h2 id="开发环境">开发环境</h2>
<ul>
<li>开发工具:Pycharm 2020.1</li>
<li>开发语言:Python 3.8.0</li>
<li>Web框架:Django 3.0.6</li>
<li>数据库:MySQL5.7</li>
<li>操作系统:Windows 10</li>
</ul>
<h2 id="项目实战">项目实战</h2>
<h3 id="1创建项目sms">1.创建项目(sms)</h3>
<p>File->New Project->Django</p>
<p><img src="https://img-blog.csdnimg.cn/20200510160249348.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTM3MzcxMzI=,size_16,color_FFFFFF,t_70#pic_center" alt="" loading="lazy"></p>
<p>稍等片刻,项目的目录结构如下图</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMDkvNFJBdGVJc3pTblp1cUs5LnBuZw?x-oss-process=image/format,png#pic_center" alt="" loading="lazy"></p>
<p>项目创建后确认是否已安装Django和mysqlclient解释器,如何确认?file->Settings</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMDkvbHpDYW5taE1yN0ZUWWpvLnBuZw?x-oss-process=image/format,png#pic_center" alt="" loading="lazy"></p>
<p>如果没有请在Terminal终端输入以下命令完成安装</p>
<pre><code>pip install django
pip install mysqlclient
</code></pre>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMDkvd3pWUUpvRUxhR2sycHM1LnBuZw?x-oss-process=image/format,png#pic_center" alt="" loading="lazy"></p>
<p>如果在执行pip install 报错Read time out请设置延长下超时时间,默认15s,网络不好情况下很易超时</p>
<pre><code>pip --default-timeout=180 install -U django
pip --default-timeout=180 install -U mysqlclient
</code></pre>
<p>参数-U是--upgrade简写,把安装的包升级到最新版本</p>
<h3 id="2创建应用sims">2.创建应用(sims)</h3>
<p>打开Pycharm的Terminal终端,输入以下命令创建sims应用</p>
<pre><code>python manage.py startapp sims
</code></pre>
<p>应用创建后要在项目的settings.py文件里的INSTALLED_APPS下面添加smis完成应用注册</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMTAvNDZuSUxCcllwN0FUYUdELnBuZw?x-oss-process=image/format,png#pic_center" alt="" loading="lazy"></p>
<h3 id="3django配置mysql">3.Django配置MySQL</h3>
<p>在本地MySQL创建sms数据库,修改项目的settings连接信息由默认的sqlite修改为MySQL</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMDkvSHEzOVVMS2c2QlRzRjF6LnBuZw?x-oss-process=image/format,png#pic_left" alt="" loading="lazy"></p>
<pre><code class="language-python">DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'sms',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': 3306
}
}
</code></pre>
<p>测试连接,依次点击Pycharm右上角的Database->+->Data Source->MySQL</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMDkvZjZOejhaVmxJMVFNTFUzLnBuZw?x-oss-process=image/format,png#pic_center" alt="" loading="lazy"></p>
<p>下载连接驱动和配置数据库连接信息</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMDkvYzJ2ZDYzN1RlMU1md2l0LnBuZw?x-oss-process=image/format,png#pic_center" alt="" loading="lazy"></p>
<p>点击Test Connection测试连接,连接通过点击OK出现如下的结构信息表示连接本地MySQL成功</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMDkvWTVmeXNYbDE0bm9aQ0dnLnBuZw?x-oss-process=image/format,png#pic_left" alt="" loading="lazy"></p>
<h3 id="4数据模型创建m">4.数据模型创建(M)</h3>
<p>在应用sims下models.py添加Student模型</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMTAvUDE4cWpYNjNuTzJoZWRCLnBuZw?x-oss-process=image/format,png#pic_center" alt="" loading="lazy"></p>
<pre><code class="language-python">class Student(models.Model):
student_no = models.CharField(max_length=32, unique=True)
student_name = models.CharField(max_length=32)
</code></pre>
<h3 id="5数据模型迁移">5.数据模型迁移</h3>
<p>Terminal终端输入以下两条命令,其作用第一条生成文件记录模型的变化;第二条是将模型变化同步至数据库,我们可以在数据库生成对应的表结构。</p>
<pre><code>python manage.py makemigrations sims
python manage.py migrate sims
</code></pre>
<p>生成数据表结构如下所示</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMTAvUmNrUWw0eEJkejZNaksyLnBuZw?x-oss-process=image/format,png#pic_center" alt="" loading="lazy"></p>
<h3 id="6路由配置">6.路由配置</h3>
<p>本质可以理解请求路径url和处理方法的映射配置,首先在项目sms的urls.py文件中添加sims的路由配置</p>
<pre><code class="language-python">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'))
]
</code></pre>
<p>然后在sims添加一个名为urls.py的文件,添加路由配置如下</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMTAvVlVhck1iR0VTMXVwMmRZLnBuZw?x-oss-process=image/format,png#pic_center" alt="" loading="lazy"></p>
<pre><code class="language-python"># 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)
]
</code></pre>
<h3 id="7处理函数v">7.处理函数(V)</h3>
<p>在应用sims的视图层文件views.py添加对应学生信息增删改查的处理函数,这里我使用的原生SQL,便于深入理解其执行过程。后面有时间我会在github上添加Django框架提供的操作数据库方式。</p>
<pre><code class="language-python">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)", )
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", )
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",
)
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", )
conn.commit()
returnredirect('../')
</code></pre>
<h3 id="8模板页面t">8.模板页面(T)</h3>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMTAvWEdka1d4dnlUS1JPN0FpLnBuZw?x-oss-process=image/format,png#pic_center" alt="" loading="lazy"></p>
<ul>
<li><strong>学生信息列表页</strong></li>
</ul>
<pre><code class="language-html"><!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>
</code></pre>
<ul>
<li><strong>学生信息新增页</strong></li>
</ul>
<pre><code class="language-html"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生添加</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>姓名</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>
</code></pre>
<ul>
<li><strong>学生信息编辑页</strong></li>
</ul>
<pre><code class="language-html"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生编辑</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>姓名</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>
</code></pre>
<h3 id="9启动web服务测试">9.启动web服务测试</h3>
<p>Terminal终端输入以下命令启动web服务</p>
<pre><code class="language-html">python manage.py runserver
</code></pre>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMTAvTTRlZ242NWsyTmhPekxWLnBuZw?x-oss-process=image/format,png#pic_center" alt="" loading="lazy"></p>
<p>服务启动后,打开浏览器输入http://127.0.0.1:8000/sims/即可进入学生信息管理列表页</p>
<h2 id="结语">结语</h2>
<p>至此,基于Python+Django+MySQL环境搭建一个拥有增删改查功能的Python Web就完成了。希望能够真正帮到大家快速入门Python Web开发。如果在搭建过程中您有遇到什么问题,欢迎在下方留言,看到我会立即回复的!可以的话给个关注哦,谢谢您!</p>
<h2 id="附录">附录</h2>
<p>最后附上项目整个源码的github仓库地址 https://github.com/hxrui/python-diango-web.git,欢迎star交流学习。</p><br><br>
来源:https://www.cnblogs.com/haoxianrui/p/12861765.html
頁:
[1]