Exemplo n.º 1
0
 def put(self, request, review_pk):
     """
     이미지는 multipart/form-data로 보내주세요! Key 값은 "images" 입니다.
     """
     user = is_logged_in(request)
     review = self.get_object(review_pk)
     if user != review.user:
         return Response(status=403)
     serializers = ReviewSerializers(instance=review, data=request.data)
     serializers.is_valid(raise_exception=True)
     review = serializers.save(
         user=user,
         perfume=review.perfume
     )
     for image in review.images.all():
         fp = os.path.join('media', 'review', 'original', f'{image.pk}.webp')
         os.remove(fp)
         image.delete()
     try:
         for img_file in dict((request.data).lists())['images']:
             with PILImage.open(img_file) as im:
                 im.save('tmp.webp', 'webp')
             image = Image.objects.create()
             image.original.save(f'{image.pk}.webp', File(open('tmp.webp', 'rb')))
             review.images.add(image)
     finally:
         return Response(status=200, headers={'Access-Control-Allow-Headers': 'token'})
Exemplo n.º 2
0
    def test_backend_image_attachments(self):
        message = EmailMessage('subject', 'body', '*****@*****.**',
                               ['*****@*****.**'])

        filename = os.path.join(os.path.dirname(__file__), 'static/dummy.png')
        fileobj = File(open(filename, 'rb'), name='dummy.png')
        image = MIMEImage(fileobj.read())
        image.add_header('Content-Disposition', 'inline', filename='dummy.png')
        image.add_header('Content-ID', '<{dummy.png}>')
        message.attach(image)
        message.send()

        email = Email.objects.latest('id')
        self.assertEqual(email.attachments.count(), 1)
        self.assertEqual(email.attachments.all()[0].name, 'dummy.png')
        self.assertEqual(email.attachments.all()[0].file.read(), image.get_payload().encode())
        self.assertEqual(email.attachments.all()[0].headers.get('Content-ID'), '<{dummy.png}>')
        self.assertEqual(email.attachments.all()[0].headers.get('Content-Disposition'), 'inline; filename="dummy.png"')
Exemplo n.º 3
0
    def test_backend_image_attachments(self):
        message = EmailMessage('subject', 'body', '*****@*****.**',
                               ['*****@*****.**'])

        filename = os.path.join(os.path.dirname(__file__), 'static/dummy.png')
        fileobj = File(open(filename, 'rb'), name='dummy.png')
        image = MIMEImage(fileobj.read())
        image.add_header('Content-Disposition', 'inline', filename='dummy.png')
        image.add_header('Content-ID', '<{dummy.png}>')
        message.attach(image)
        message.send()

        email = Email.objects.latest('id')
        self.assertEqual(email.attachments.count(), 1)
        self.assertEqual(email.attachments.all()[0].name, 'dummy.png')
        self.assertEqual(email.attachments.all()[0].file.read(), image.get_payload().encode())
        self.assertEqual(email.attachments.all()[0].headers.get('Content-ID'), '<{dummy.png}>')
        self.assertEqual(email.attachments.all()[0].headers.get('Content-Disposition'), 'inline; filename="dummy.png"')
Exemplo n.º 4
0
 def post(self, request, perfume_pk):
     """
     이미지는 multipart/form-data로 보내주세요! Key 값은 "images" 입니다.
     """
     user = is_logged_in(request)
     try:
         perfume = Perfume.objects.get(pk=perfume_pk)
     except:
         return Response(status=404)
     serializers = ReviewSerializers(data=request.data)
     serializers.is_valid(raise_exception=True)
     review = serializers.save(
         user=user,
         perfume=perfume,
     )
     try:
         for img_file in dict((request.data).lists())['images']:
             with PILImage.open(img_file) as im:
                 im.save('tmp.webp', 'webp')
             image = Image.objects.create()
             image.original.save(f'{image.pk}.webp', File(open('tmp.webp', 'rb')))
             review.images.add(image)
     finally:
         return Response({'review_id': review.pk}, status=200)
Exemplo n.º 5
0
def server_authentication(request):
    if request.method == 'POST':
        card_id = request.POST['card_id']
        try:
            member = Member.objects.get(card_id=card_id)
            last_image_name = ''
            # save images to /tmp folder
            for face_key in request.FILES:
                last_image_name = face_key
                data = request.FILES[face_key]
                face = ImageFile(data)
                face_path = 'tmp/' + str(data)
                if default_storage.exists(face_path):
                    default_storage.delete(face_path)
                default_storage.save(face_path, face)

            # get result of predict list images
            list_predicts = face_recognize.recognition(member.recognize_label)
            # list_predicts = []
            if len(list_predicts):
                last_image_name = list_predicts[0][0]

            # check threshold
            result_auth = False
            f_name = None
            for file_name, conf in list_predicts:
                print(conf)
                if conf < member.threshold:
                    result_auth = True
                    f_name = file_name
                    break
            # publish result auth to mqtt topic /pas/mqtt/icse/auth
            result_auth_payload = 'OK' if result_auth else 'FAIL'
            mqtt.publish(const.MQTT_AUTH_TOPIC, result_auth_payload)
            print("ok")
            # get latest logs to check user in or out
            try:
                # TODO: check last log for new day, not last day
                last_log = Logs.objects.filter(
                    member_id=member.id).latest('time_stamp')
                is_go_in = False if last_log.is_go_in else True
            except Logs.DoesNotExist:
                is_go_in = True

            member.is_in_lab = True if is_go_in else False
            member.save()

            # publish latest user scan to web browser
            latest_user_scan_payload = {
                'member_name': member.name,
                'state': 'Goes In' if is_go_in else 'Goes Out'
            }
            mqtt.publish(const.MQTT_LATEST_USER_SCAN,
                         json.dumps(latest_user_scan_payload))

            # save logs
            log = Logs(
                time_stamp=timezone.now(),
                member=member,
                result_auth=result_auth,
                is_go_in=is_go_in,
            )
            f_name = f_name if result_auth else last_image_name
            file_path = os.path.join(const.TMP_FOLDER, f_name)
            file_data = File(open(file_path, 'rb'))
            log.image.save(f_name, file_data, save=True)
            log.save()
        except Member.DoesNotExist:
            print("member does not exist")
            mqtt.publish(const.MQTT_AUTH_TOPIC, 'FAIL')
            mqtt.publish(const.MQTT_MEMBER_DOES_NOT_EXIST, '1')
        return HttpResponse("POST request success")
    return HttpResponse("Not valid request type!")
Exemplo n.º 6
0
def add_data(post, file_name):
    img = BlogPhoto.objects.create(post = post)
    with open(os.path.join(path_temp, file_name), 'rb') as f:
        myfile = File(f)
        img.photo.save(name=file_name, content=myfile)
    print('к посту {} \nдобавлен файл: {} \nurl: {}'.format(img.post.title, img.photo.name, img.photo.url))