首先这个项目是属于我的省级大创(大学生创新实验计划)的,最终实现的目标是可以上传图片作为人来能识别库,并且人脸识别结果用语音报出来。
现在第一步,先实现数据库的对接,这一次用MySQL数据库,过几天也许会考虑改成Redis来存放,毕竟存放如数据库的是图片在服务器端的存放地址,而不可能是整个图片的信息;毕竟这是一个键值对,完全可以用Redis的String来存放。
现在来具体介绍下views.py文件:
from django.shortcuts import render
from .models import Name_Picture
from django.http import HttpResponse, HttpResponseRedirect
import os
def data(request):
datas = Name_Picture.get_all()
context = {
'datas': datas,
}
return render(request, 'data.html', context=context)
def index(request):
return render(request, 'index.html')
def upload_file(request):
if request.method == "POST": # 请求方法为POST时,进行处理
myFile = request.FILES.get("myfile", None) # 获取上传的文件,如果没有文件,则默认为None
if not myFile:
return HttpResponse("no files for upload!")
destination = open(os.path.join('facePhoto', myFile.name), 'wb+') # 打开特定的文件进行二进制的写操作
for chunk in myFile.chunks(): # 分块写入文件
destination.write(chunk)
destination.close()
pictureLocation = os.path.join('facePhoto', myFile.name)
data = Name_Picture()
data.picture = pictureLocation
username = request.POST['username']
data.names = username
data.save()
return HttpResponseRedirect('/index/')
elif request.method == 'GET':
return render(request, 'index.html')
这里写了三个函数:data、index、upload;分别负责显示数据库的数据data、上传照片和人名index、上传文件功能的函数upload。注意看上传文件函数:
def upload_file(request):
if request.method == "POST": # 请求方法为POST时,进行处理
myFile = request.FILES.get("myfile", None) # 获取上传的文件,如果没有文件,则默认为None
if not myFile:
return HttpResponse("no files for upload!")
destination = open(os.path.join('facePhoto', myFile.name), 'wb+') # 打开特定的文件进行二进制的写操作
for chunk in myFile.chunks(): # 分块写入文件
destination.write(chunk)
destination.close()
pictureLocation = os.path.join('facePhoto', myFile.name)
data = Name_Picture()
data.picture = pictureLocation
username = request.POST['username']
data.names = username
data.save()
return HttpResponseRedirect('/index/')
elif request.method == 'GET':
return render(request, 'index.html')
由于第一次打开页面会使用get请求,第二次及以后才是post请求,所以要用if-else分开来写,当为post时上传文件,这一段是负责上传文件的:
# 获取上传的文件,如果没有文件,则默认为None
myFile = request.FILES.get("myfile", None)
# 没有上传文件时的操作
if not myFile:
return HttpResponse("no files for upload!")
# 打开特定的文件进行二进制的写操作
destination = open(os.path.join('facePhoto', myFile.name), 'wb+')
# 分块写入文件
for chunk in myFile.chunks():
destination.write(chunk)
destination.close()
下面是通过ORM映射入数据库的步骤:
# 记录图片保存的路径
pictureLocation = os.path.join('facePhoto', myFile.name)
# 从models.py传过来模型
data = Name_Picture()
data.picture = pictureLocation
# 传入数据
username = request.POST['username']
data.names = username
# 保存数据
data.save()
# 刷新页面
return HttpResponseRedirect('/index/')
关于views.py文件就是这么多,下面看下models.py文件的定义。
这是models.py文件:
from django.db import models
class Name_Picture(models.Model):
names = models.CharField(max_length=128, verbose_name='姓名')
picture = models.CharField(max_length=128, verbose_name='picture')
def __str__(self):
return '<names: {}>'.format(self.names)
@classmethod
def get_all(cls):
return cls.objects.all()
def get_name(self):
return self.names
就定义了两个字段,names用于存放姓名,pictures用于存放图片路径。下面定义的都是些获取结果等可能用到的函数和方法,也不是很多。
urls.py负责映射定义了网络地址(url),文件也不长:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from faceDataManagement.views import data, upload_file, index
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', index),
url(r'^data/', data),
url(r'^uploadFile/', upload_file)
]
可以看到有四条url路径,分别对应着后台管理admin、上传数据(图片和姓名)index、查看数据库data、还有上传文件功能。
还有一个文件是admin.py,用于定义后台管理页面:
from django.contrib import admin
from .models import Name_Picture
class faceAdmin(admin.ModelAdmin):
list_display = (
'picture',
'names',
)
fieldsets = (
(None, {
'fields': (
'names',
'picture'
)
}),
)
list_editable = ['names']
admin.site.register(Name_Picture, faceAdmin)
可以看到结果是这样的:
还有两张html如下:
index对应的上传页面:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="favicon.ico" rel="shortcut icon">
<meta charset="UTF-8">
<title>上传照片</title>
</head>
<body>
<form enctype="multipart/form-data" action="/uploadFile/" method="POST">
{% csrf_token %}
<input type="text" placeholder="姓名" name="username">
<input type="file" name="myfile" />
<input type="submit" value="上传"/>
</form>
</body>
</html>
如下所示:
还有data页面,也比较简单:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>所有数据</title>
</head>
<body>
<ul>
{% for data in datas %}
<li>姓名:{{ data.names }}-图片信息:{{ data.picture }}</li>
{% endfor %}
</ul>
</body>
</html>
如下所示:
最后是settings.py文件一揽,定义了数据库和汉化相关的内容:
"""
Django settings for faceWeb project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$rwh(qrlx1)l^17n-pgl-3*7zu#g=d6p&*0ehxx8cv=%o$8!bo'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'faceDataManagement'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'faceWeb.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'faceWeb.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'face',
'USER': 'root',
'PASSWORD': '56167823',
'HOST': 'localhost',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR, 'cascades')
]
END