基于Django框架实现前后端分离(⼆)
基于Django实现后端API开发
后端APP应⽤(staff)的实现
本应⽤为项⽬中的员⼯管理部分,主要是实现某公司员⼯信息的增删改查。
建⽴模型
Django中的模型对应数据库中的表结构,本应⽤将使⽤四个表:员⼯信息表(t_staff_info),员⼯证书表(t_staff_cert),⽂件表(t_edoc),数据字典表(t_dict_all),其中⽂件表与数据字典表为项⽬公⽤表,将在后⽂中详细介绍。
kptfrom django.db import models
from django.utils import timezone
# Create your models here.
class TStaffCert(models.Model):
staff = models.ForeignKey('TStaffInfo',model.DO_NOTHING,blank=True, null=True,db_column='staff_id')
staffId = models.IntegerField(db_column='staff_id',blank=True, null=True)
certType = models.IntegerField(db_column='cert_type',blank=True, null=True)
certId = models.IntegerField(db_column='cert_id',blank=True, null=True)
certName = models.CharField(db_column='cert_name',max_length=128, blank=True, null=True)
certGrade = models.IntegerField(db_column='cert_grade',blank=True, null=True)
certMajor = models.IntegerField(db_column='cert_major',blank=True, null=True)
certFulltime = models.IntegerField(db_column='cert_fulltime',blank=True, null=True)
certCode = models.CharField(db_column='cert_code',max_length=128, blank=True, null=True)
certState = models.IntegerField(db_column='cert_state',blank=True, null=True)
certPerson = models.CharField(db_column='cert_person',max_length=50, blank=True, null=True)
certOrg = models.CharField(db_column='cert_org',max_length=50, blank=True, null=True)
certIssuer = models.CharField(db_column='cert_issuer',max_length=50, blank=True, null=True)
certDate = models.DateField(db_column='cert_date',blank=True, null=True)
validDate = models.DateField(db_column='valid_date',blank=True, null=True)
createDate = models.DateTimeField(db_column='create_date',blank=True, null=True,w())
modifyDate = models.DateTimeField(db_column='modify_date',blank=True, null=True,w())
sts = models.IntegerField()经典电影 推荐
class Meta:
managed =Fal
db_table ='t_staff_cert'
class TStaffInfo(models.Model):
staffCode = models.CharField(db_column='staff_code',help_text='⼯号',max_length=32, blank=True, null=True)
staffName = models.CharField(db_column='staff_name',,help_text='姓名'max_length=128, blank=True, null=True)
nation = models.CharField(db_column='nation',max_length=64, blank=True, null=True)
bizGroup = models.CharField(db_column='biz_group',max_length=64, blank=True, null=True)
bizDept = models.CharField(db_column='biz_dept',max_length=64, blank=True, null=True)
dept = models.CharField(db_column='dept',max_length=64, blank=True, null=True)
enrollDate = models.DateField(db_column='enroll_date',blank=True, null=True)flowrve
graduateDate = models.DateField(db_column='graduate_date',blank=True, null=True)
workingDate = models.DateField(db_column='working_date',blank=True, null=True)
birthday = models.DateField(db_column='birthday', blank=True, null=True)
idCardCode = models.CharField(db_column='id_card_code', max_length=32, blank=True, null=True)
gender = models.IntegerField(db_column='gender', blank=True, null=True)
email = models.CharField(db_column='email',max_length=64, blank=True, null=True)
college = models.CharField(db_column='college',max_length=64, blank=True, null=True)
major = models.CharField(db_column='major',max_length=64, blank=True, null=True)
diploma = models.CharField(db_column='diploma',max_length=64, blank=True, null=True)
diplomaCode = models.CharField(db_column='diploma_code',max_length=64, blank=True, null=True)
diplomaCode = models.CharField(db_column='diploma_code',max_length=64, blank=True, null=True)
degree = models.CharField(db_column='degree',max_length=64, blank=True, null=True)
degreeCode = models.CharField(db_column='degree_code',max_length=64, blank=True, null=True)
majorType = models.CharField(db_column='major_type',max_length=64, blank=True, null=True)
contractUntil = models.DateField(db_column='contract_until',blank=True, null=True)
idCardUntil = models.DateField(db_column='id_card_until',blank=True, null=True)
certFulltime = models.IntegerField(db_column='cert_fulltime',blank=True, null=True)
employer = models.CharField(db_column='employer',max_length=64, blank=True, null=True)
mobilePhone = models.CharField(db_column='mobile_phone',max_length=64, blank=True, null=True)
jobState = models.IntegerField(db_column='job_state',blank=True, null=True)
insuranceCode = models.CharField(db_column='insurance_code',max_length=64, blank=True, null=True)
insuranceFrom = models.DateField(db_column='insurance_from',blank=True, null=True)
insuranceTo = models.DateField(db_column='insurance_to',blank=True, null=True)
sts = models.IntegerField(db_column='sts',blank=True, null=True)
comment = models.CharField(db_column='comment',max_length=1024, blank=True, null=True)
createDate = models.DateTimeField(db_column='create_date',blank=True, null=True)
modifyDate = models.DateTimeField(db_column='modify_date',blank=True, null=True,w())
class Meta:
ogre
managed =Fal
db_table ='t_staff_info'
代码中db_column表⽰数据库中列名称,如果需要将数据库表的列名做映射,则使⽤该字段,default表⽰该字段的默认值;help_text表⽰注释。
其中:
staff = models.ForeignKey('TStaffInfo',model.DO_NOTHING,blank=True, null=True)
models.ForeignKey表⽰外键,该外键关联TStaffInfo。
链接myql数据库
Django默认使⽤的数据库是的sqlite3,如果项⽬中需要链接其他数据库则需要修改tting.py⽂件中的DATABASES财政悬崖
# Django默认数据库
DATABASES ={
'default':{
'ENGINE':'django.db.backends.sqlite3',
'NAME': BASE_DIR /'db.sqlite3',
}
}
# 使⽤mysql数据库
DATABASES ={
# 'default': dj_databa_url.par('sqlite:///' + db_path),
'default':{
'ENGINE':'django.sql',
'NAME':'edoc_dev',# 数据库名
'USER':'edoc',# ⽤户名
'PASSWORD':'edoc123',# 密码
'HOST':'',#数据库的ip地址
'PORT':'3306',# 端⼝默认为3306
}
}
序列化模型
Django在Python的web框架中是出了名的重,⽽DRF即Django REST Framwork更重,在遇到复杂的数据处理需求是,它的序列化设计⼗分繁琐。故在项⽬中数据处理全部由⾃⼰书写。序列化只设计swagger⽂档部分。具体swagger后⽂会详细介绍
配置路由
由于⼀个项⽬中会有多个APP应⽤,每个应⽤⼜有多个接⼝,可以使⽤分路由的⽅式来美化代码,使得主路由⽂件urls.py不⾄于太过于冗长。
主路由
ib import admin
from django.urls import include, path
# urlpatterns required for ttings values
required_urlpatterns =[
path('admin/', admin.site.urls),
# path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
]
urlpatterns =[
# ⼈员
path('cms/ur/', include('staff.urls')),
]+ required_urlpatterns
分路由:
from django.urls import include, path
from staff import views
from uters import SimpleRouter
class StandardRouter(SimpleRouter):
def__init__(lf, trailing_slash='/?'):
super(StandardRouter, lf).__init__()
router = StandardRouter()
urlpatterns =[
# ⼈员资料管理
minimotorpath('', include(router.urls)),
# path('', StaffViews.StaffList.as_view()),
# url(r'^detail', views.Staffdetail.as_view()),
# url(r'^add', views.Staffadd.as_view()),
# url(r'^update', views.Staffupdate.as_view()),
# url(r'^delete', views.delete.as_view()),
# url(r'^exportWord', portWord.as_view()),
# url(r'^exportExcel', portExcel.as_view()),
# url(r'^imageUpload', views.imageUpload.as_view()),
# url(r'^imageDelete', views.imageDelete.as_view()),
]
其中StandardRouter类作⽤是让url可以是“/”结尾。使⽤它时需要先在tting⽂件中添加:
#路由设置为:可以以/结尾
APPEND_SLASH=Fal
视图设计
Django的视图建议写在APP应⽤中的views.py中:
from django.http import JsonRespon
from rest_framework.decorators import action
from rest_framework import viewts宁波早教
from rest_framework.permissions import IsAuthenticated
dels import TStaffInfo
from staff import rializers
hod import get_staff_list
from drf_yasg.utils import swagger_auto_schema
class StaffViewsSet(viewts.ViewSet):
queryt = TStaffInfo.objects.all()
# lookup_field = 'slug'
# lookup_value_regex = r'[a-z0-9]+(?:-[a-z0-9]+)'
# rializer_class = rializers.StaffSerializer
def get_permissions(lf):
"""
Instantiates and returns the list of permissions that this view requires.
"""
permission_class =[]
return[permission()for permission in permission_class]
# 员⼯信息列表页
@swagger_auto_schema(
request_body=rializers.ListRequestSerializer,
respons={
'200': rializers.ListResponsSerializer,
'400':"Bad Request"
},
# curity=[],
operation_id='列表页',
operation_description='员⼯信息列表页',
tags=['员⼯管理系统'],
)
@action(detail=Fal,
methods=['post'],
url_name='list',
url_path='list',
)
def list_(lf, request,format=None):
acc = request.data
ur = request.ur
print(ur)
r = rializers.StaffSerializer.data
staff = get_staff_list.Staffinfo()
result = _list_data(acc)
return JsonRespon(result, json_dumps_params={'ensure_ascii':Fal})
其中get_staff_list为⾃⼰写的数据处理脚本。它包含接⼝中所需要的所有⽅法。上述代码中使⽤了get_staff_list脚本中的Staffinfo类下⾯的get_list_data⽅法获取列表业数据。
get_staff_list.py脚本代码如下:
dels import TEdoc, TDict, TStaffCert, TStaffInfo
paginator import Paginator
from django.db import connection
from dels import Q
dels import TDictAll
import time, datetime
def get_time_now():
a = time.localtime(time.time())
b = time.strftime('%Y-%m-%d %H:%M:%S', a)
datetimes = datetime.datetime.strptime(b,'%Y-%m-%d %H:%M:%S')
return datetimes
def formart_return_data(data, err=0, status=200, msg=''):韩国语等级考试报名
if not err:
return{"result": data,"status": status,'msg': msg}
el:
return{"result": data,"status": status,'msg': msg}
class Staffinfo:
def__init__(lf):
lf.cursor = connection.cursor()
@classmethod
def transform_time(lf, input_t,type):
# 时间格式转换
# type=s 将datatime格式转为时间戳(单位年)
# type=y 将时间戳(单位年)为datatime格式
hfg# 将年限转换为时间格式
if type=='ts':
d = time.strftime("%Y-%m-%d", time.localtime())
y =int(str(d).split('-')[0])- input_t
date_ = f'{y}-12-31'
print('开始时间:', date_)
return date_
if type=='te':
d = time.strftime("%Y-%m-%d", time.localtime())
y =int(str(d).split('-')[0])- input_t
date_ = f'{y}-1-1'
print('结束时间:', date_)
return date_
# 将时间转换为年限
if type=='s':
# try:
# t = time.mktime(time.strptime(str(input_t), '%Y-%m-%d %H:%M:%S')) # except:
# t = time.mktime(time.strptime(str(input_t), '%Y-%m-%d'))
# # now_date = get_time_now()
# now_time = time.mktime(time.strptime(str(get_time_now()),
# '%Y-%m-%d %H:%M:%S'))
t =str(input_t).split('-')[0]
now_y =str(get_time_now()).split('-')[0]
r =int(now_y)-int(t)
# r = int((now_time-t) / (60 * 60 * 24 * 365))
if r >=0:
return r
el:
return-2
if type=='S':
英文圣诞歌ts =int(input_t)
dateArray = datetime.datetime.fromtimestamp(ts)
y = dateArray.strftime("%Y-%m-%d %H:%M:%S")
return y
if type=='d':
ts =int(input_t)
dateArray = datetime.datetime.fromtimestamp(ts)
y = dateArray.strftime("%Y-%m-%d")