在Django RestFrameWork中设置的模型视图中的图像水印

时间:2020-05-06 07:07:15

标签: python django django-rest-framework django-views

我正在使用模型视图集开发一个简单的Django rest框架应用程序。首先,我输入图像,名称和其他详细信息,然后保存到postgresql并在Google表格中进行更新。 所以我试图在不使用任何html文件的情况下将输入图像的水印放入模型视图集中。 我已经在python中通过了水印包,但无法掌握。 因此,任何人都可以帮助我使用模型视图集添加输入图像的水印

这是我的views.py

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from rest_framework.parsers import JSONParser
from .models import Article
from .serializers import ArticleSerializer
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework import mixins
from rest_framework.authentication import TokenAuthentication, BasicAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets
from django.shortcuts import get_object_or_404
# Create your views here.
from PIL import Image
from rest_framework.decorators import action
from rest_framework.response import Response

import gspread
from oauth2client.service_account import ServiceAccountCredentials
from django.http import HttpResponse, Http404

scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('Review-4016be63eaa5.json', scope)
client = gspread.authorize(creds)

# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("review").sheet1





class ArticleViewSet(viewsets.ModelViewSet):
    serializer_class = ArticleSerializer
    queryset = Article.objects.all()

    def create(self, request):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            #print(serializer.data)
            serializer.save()



            print(serializer.data)

            t = list()
            for k, v in serializer.data.items():
                t.append(v)
            print(t)
            list_of_hashes = sheet.get_all_values()
            print(list_of_hashes)
            sheet.insert_row(t, len(list_of_hashes)+1)

            #Account.objects.create_user(**serializer.validated_data)
            return Response(
                serializer.data, status=status.HTTP_201_CREATED
            )

        return Response({
            'status': 'Bad request',
            'message': 'Account could not be created with received data.'
        }, status=status.HTTP_400_BAD_REQUEST)

def update(self, request, pk=None):
    article = Article.objects.get(pk=pk)
    serializer = ArticleSerializer(article, data=request.data)
    if serializer.is_valid():
        serializer.save()
        print(serializer.data)
        c=sheet.col_values(1)
        t = list()
        for k, v in serializer.data.items():
            t.append(v)
        rownum=1
        print(c)
        print(t)
        r=str(t[0])
        if r in c:
            print("inside r", r)
            rownum = c.index(r)+1

        sheet.delete_rows(rownum)
        sheet.insert_row(t, rownum)

        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def destroy(self, request, *args, **kwargs):
    try:
        instance = self.get_object()
        print(instance.id)
        print(type(instance.id))
        c = sheet.col_values(1)

        rownum = 2
        print(c)
        print(type(instance))
        r=str(instance.id)
        if r in c:
            print("inside r", r)
            rownum = c.index(r) + 1

            sheet.delete_rows(rownum)

        self.perform_destroy(instance)
    except Http404:
        pass
    return Response(status=status.HTTP_204_NO_CONTENT)

这是我的Models.py

from django.db import models

# Create your models here.

class Article(models.Model):
    name = models.CharField(max_length=100)
    gender = models.CharField(max_length=100)
    age = models.IntegerField()
    image = models.ImageField()
    date=models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.id)


1 个答案:

答案 0 :(得分:1)

您应该尝试Image.paste()方法

image = Image.open('image.jpg')
watermark = Image.open('watermark.png')
image.paste(watermark, (x, y), watermark)