최지우

비디오 관련 api 수정 및 비디오 저장 프로세스 예시

1 -# Generated by Django 3.1.2 on 2020-11-04 11:24 1 +# Generated by Django 3.1.2 on 2020-11-13 10:30
2 2
3 from django.db import migrations, models 3 from django.db import migrations, models
4 -import django.db.models.deletion
5 import django.utils.timezone 4 import django.utils.timezone
6 5
7 6
...@@ -35,27 +34,24 @@ class Migration(migrations.Migration): ...@@ -35,27 +34,24 @@ class Migration(migrations.Migration):
35 ], 34 ],
36 ), 35 ),
37 migrations.CreateModel( 36 migrations.CreateModel(
38 - name='Video', 37 + name='Lock',
39 fields=[ 38 fields=[
40 - ('vid_id', models.IntegerField(primary_key=True, serialize=False)), 39 + ('id', models.IntegerField(primary_key=True, serialize=False)),
41 - ('created', models.DateTimeField(default=django.utils.timezone.now)), 40 + ('state', models.BooleanField(default=True)),
42 - ('s3_link', models.CharField(max_length=255)),
43 ], 41 ],
44 ), 42 ),
45 migrations.CreateModel( 43 migrations.CreateModel(
46 name='Record', 44 name='Record',
47 fields=[ 45 fields=[
48 - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 46 + ('id', models.IntegerField(primary_key=True, serialize=False)),
49 ('recording', models.BooleanField(default=True)), 47 ('recording', models.BooleanField(default=True)),
50 - ('door', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.door')),
51 ], 48 ],
52 ), 49 ),
53 migrations.CreateModel( 50 migrations.CreateModel(
54 - name='Lock', 51 + name='Video',
55 fields=[ 52 fields=[
56 - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 53 + ('vid_name', models.CharField(max_length=255, primary_key=True, serialize=False)),
57 - ('state', models.BooleanField(default=True)), 54 + ('created', models.DateTimeField(default=django.utils.timezone.now)),
58 - ('door', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.door')),
59 ], 55 ],
60 ), 56 ),
61 ] 57 ]
......
1 -# Generated by Django 3.1.2 on 2020-11-10 10:44
2 -
3 -from django.db import migrations, models
4 -
5 -
6 -class Migration(migrations.Migration):
7 -
8 - dependencies = [
9 - ('api', '0001_initial'),
10 - ]
11 -
12 - operations = [
13 - migrations.RemoveField(
14 - model_name='lock',
15 - name='door',
16 - ),
17 - migrations.RemoveField(
18 - model_name='record',
19 - name='door',
20 - ),
21 - migrations.AlterField(
22 - model_name='lock',
23 - name='id',
24 - field=models.IntegerField(primary_key=True, serialize=False),
25 - ),
26 - migrations.AlterField(
27 - model_name='record',
28 - name='id',
29 - field=models.IntegerField(primary_key=True, serialize=False),
30 - ),
31 - ]
...@@ -11,9 +11,8 @@ class Device(models.Model) : ...@@ -11,9 +11,8 @@ class Device(models.Model) :
11 created = models.DateTimeField(default = timezone.now) 11 created = models.DateTimeField(default = timezone.now)
12 12
13 class Video(models.Model) : 13 class Video(models.Model) :
14 - vid_id = models.IntegerField(primary_key = True) 14 + vid_name = models.CharField(max_length = 255, primary_key = True)
15 created = models.DateTimeField(default = timezone.now) 15 created = models.DateTimeField(default = timezone.now)
16 - s3_link = models.CharField(max_length = 255)
17 16
18 class Lock(models.Model) : 17 class Lock(models.Model) :
19 id = models.IntegerField(primary_key = True) 18 id = models.IntegerField(primary_key = True)
......
1 +import os
2 +import boto3
3 +import botocore
4 +import time
5 +import datetime
6 +from django.core import serializers
7 +
8 +from api.models import Video, Record
9 +from api.serializers import VideoSerializer, RecordSerializer
10 +'''
11 +import picamera
12 +from boto3.session import Session
13 +from src.settings import AWS_REGION, S3_ACCESS_URL, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_STORAGE_BUCKET_NAME
14 +'''
15 +
16 +def record() :
17 + path = '/home/pi/recorded' # 저장할 경로
18 + state = True
19 +
20 + while state :
21 + target = Record.objects.get(id = 1)
22 + serializer = RecordSerializer(target, many = False)
23 + state = serializer.data['recording']
24 + with picamera.Picamera() as camera :
25 + camera.resolution = [320,240]
26 + now = datetime.datetime.now()
27 + vid_name = now.strftime('%Y%m%d-%H%M%S')
28 +
29 + vid_path = path + '/' + vid_name + '.h264'
30 + camera.start_recording(output = vid_path)
31 + camera.wait_recording(10)
32 + camera.stop_recording()
33 +
34 + s3 = boto3.client('s3', region_name = 'ap-northeast-2')
35 + s3.upload_file(Filename = vid_path, Bucket = S3_STORAGE_BUCKET_NAME, Key = vid_name)
36 +
37 + uploadVideo = {}
38 + uploadVideo['vid_name'] = vid_name
39 + uploadVideo['created'] = now
40 + serializer = VideoSerializer(data = uploadVideo)
41 + serializer.save()
42 +
43 + os.remove(vid_path)
...\ No newline at end of file ...\ No newline at end of file
1 import boto3 1 import boto3
2 +import botocore
3 +import threading
2 from django.http import HttpResponse 4 from django.http import HttpResponse
3 from django.core import serializers 5 from django.core import serializers
4 from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist 6 from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist
5 from django.shortcuts import render 7 from django.shortcuts import render
6 8
9 +from api.videorecord import record
7 from api.models import Video, Device, History, Lock, Record, Door 10 from api.models import Video, Device, History, Lock, Record, Door
8 from api.serializers import VideoSerializer, DeviceSerializer, HistorySerializer, RecordSerializer 11 from api.serializers import VideoSerializer, DeviceSerializer, HistorySerializer, RecordSerializer
9 12
...@@ -17,16 +20,13 @@ from src.settings import AWS_REGION ...@@ -17,16 +20,13 @@ from src.settings import AWS_REGION
17 from src.settings import S3_ACCESS_URL 20 from src.settings import S3_ACCESS_URL
18 from src.settings import S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_STORAGE_BUCKET_NAME 21 from src.settings import S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_STORAGE_BUCKET_NAME
19 """ 22 """
23 +import time
20 from datetime import datetime, timedelta 24 from datetime import datetime, timedelta
21 # Create your views here. 25 # Create your views here.
22 26
23 # 비디오 목록 조회 27 # 비디오 목록 조회
24 class VideoList(APIView) : 28 class VideoList(APIView) :
25 def get(self, request, format = None) : 29 def get(self, request, format = None) :
26 - '''
27 - request_id = request.GET.get('last_id') # requst의 last_id 받아옴
28 - queryset = Video.objects.filter(vid_id__range = (request_id, request_id + 10)) # 쿼리셋 필터로 vid_id의 범위가 last_id ~ las_id + 10인 객체 찾기
29 - '''
30 queryset = Video.objects.all() 30 queryset = Video.objects.all()
31 serializer = VideoSerializer(queryset, many = True) 31 serializer = VideoSerializer(queryset, many = True)
32 res = { 32 res = {
...@@ -35,16 +35,16 @@ class VideoList(APIView) : ...@@ -35,16 +35,16 @@ class VideoList(APIView) :
35 return Response(res, status = status.HTTP_200_OK) 35 return Response(res, status = status.HTTP_200_OK)
36 36
37 # 비디오 수동 삭제 37 # 비디오 수동 삭제
38 - def delete(self, request, vid_id, format = None) : # request URI에 vid_id가 포함되어있음 : api/video/{vid_id} 38 + def delete(self, request, vid_name, format = None) : # request URI에 vid_name가 포함되어있음 : api/video/{vid_name}
39 try : 39 try :
40 - request_id = vid_id 40 + request_id = vid_name
41 if request_id == 'None' : 41 if request_id == 'None' :
42 raise FieldDoesNotExist 42 raise FieldDoesNotExist
43 session = boto3.session.Session(aws_access_key_id = S3_ACCESS_KEY_ID, aws_secret_access_key = S3_SECRET_ACCESS_KEY, region_name = AWS_REGION) 43 session = boto3.session.Session(aws_access_key_id = S3_ACCESS_KEY_ID, aws_secret_access_key = S3_SECRET_ACCESS_KEY, region_name = AWS_REGION)
44 s3 = session.client('s3') 44 s3 = session.client('s3')
45 45
46 - target = Video.objects.get(vid_id = request_id) 46 + target = Video.objects.get(vid_name = request_id)
47 - s3.delete_object(Bucket = S3_STORAGE_BUCKET_NAME, Key = str(target.vid_id)) 47 + s3.delete_object(Bucket = S3_STORAGE_BUCKET_NAME, Key = str(target.vid_name))
48 target.delete() 48 target.delete()
49 return Response(status = status.HTTP_200_OK) 49 return Response(status = status.HTTP_200_OK)
50 except FieldDoesNotExist as error : 50 except FieldDoesNotExist as error :
...@@ -55,9 +55,9 @@ class VideoList(APIView) : ...@@ -55,9 +55,9 @@ class VideoList(APIView) :
55 55
56 # 비디오 확인(다운로드) 56 # 비디오 확인(다운로드)
57 class VideoDownload(APIView) : 57 class VideoDownload(APIView) :
58 - def get(self, request, vid_id, format = None) : # 요청한 URI에 vid_id가 포함되어있음 ex) api/video/1 58 + def get(self, request, vid_name, format = None) : # 요청한 URI에 vid_name가 포함되어있음
59 try : 59 try :
60 - request_id = vid_id 60 + request_id = vid_name
61 if request_id == 'None' : 61 if request_id == 'None' :
62 raise FieldDoesNotExist 62 raise FieldDoesNotExist
63 download_url = S3_ACCESS_URL + str(request_id) # S3 다운로드 링크 변환 63 download_url = S3_ACCESS_URL + str(request_id) # S3 다운로드 링크 변환
...@@ -86,7 +86,7 @@ class CheckDate(APIView) : ...@@ -86,7 +86,7 @@ class CheckDate(APIView) :
86 session = boto3.session.Session(aws_access_key_id = S3_ACCESS_KEY_ID, aws_secret_access_key = S3_SECRET_ACCESS_KEY, region_name = AWS_REGION) 86 session = boto3.session.Session(aws_access_key_id = S3_ACCESS_KEY_ID, aws_secret_access_key = S3_SECRET_ACCESS_KEY, region_name = AWS_REGION)
87 s3 = session.client('s3') 87 s3 = session.client('s3')
88 for delvid in quaryset : 88 for delvid in quaryset :
89 - s3.delete_object(Bucket = S3_STORAGE_BUCKET_NAME, Key = str(delvid.vid_id)) 89 + s3.delete_object(Bucket = S3_STORAGE_BUCKET_NAME, Key = str(delvid.vid_name))
90 quaryset.delete() 90 quaryset.delete()
91 return Response(status = status.HTTP_200_OK) 91 return Response(status = status.HTTP_200_OK)
92 92
...@@ -110,6 +110,10 @@ class Recording(APIView) : ...@@ -110,6 +110,10 @@ class Recording(APIView) :
110 try : 110 try :
111 target = Record.objects.filter(id = 1) 111 target = Record.objects.filter(id = 1)
112 target.update(recording = request.data['recording']) 112 target.update(recording = request.data['recording'])
113 +
114 + if request.data['recording'] :
115 + threading.Thread(target=record).start()
116 +
113 return Response(status = status.HTTP_200_OK) 117 return Response(status = status.HTTP_200_OK)
114 except FieldDoesNotExist as error : 118 except FieldDoesNotExist as error :
115 return Response({ 119 return Response({
......
...@@ -21,7 +21,7 @@ from api import views ...@@ -21,7 +21,7 @@ from api import views
21 urlpatterns = [ 21 urlpatterns = [
22 path('admin/', admin.site.urls), 22 path('admin/', admin.site.urls),
23 path('api/video', views.VideoList.as_view()), 23 path('api/video', views.VideoList.as_view()),
24 - path('api/video/<int:vid_id>', views.VideoDownload.as_view()), 24 + path('api/video/<str:vid_name>', views.VideoDownload.as_view()),
25 path('auto/checkDate', views.CheckDate.as_view()), 25 path('auto/checkDate', views.CheckDate.as_view()),
26 path('api/setting', views.Recording.as_view()), 26 path('api/setting', views.Recording.as_view()),
27 ] 27 ]
......