首先這個項目是屬於我的省級大創(大學生創新實驗計劃)的,最終實現的目標是可以上傳圖片作爲人來能識別庫,並且人臉識別結果用語音報出來。
現在第一步,先實現數據庫的對接,這一次用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