不写注释的程序员

My_Code

不写注释的程序员

import hashlib
import json

import requests
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View

from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.uj_search.models import *
from apps.uj_search.serializers import *
from ujedu.settings import PARTNER_CODE, PARTNER_SECRET_KEY, REST_FRAMEWORK
from utils.regression_algorithm import sankeMatric
from utils.response_code import RET


"""不好意思 此处为加密数据"""

class ASINSearchView(View):

    def get(self, request):
        marketplace = request.GET.get('marketplace')
        asin_ = request.GET.get("asin")
        asin = AsinSeedApiTest()
        urlStr = asin.main(marketplace, asin_)
        print(urlStr[0])
        if len(asin_) < 10:
            return JsonResponse({"status": 404, "code": "ERROR", "message": "ASIN输入错误"})
        try:
            asin_info = requests.get(urlStr[0]).content
            asin_dict = json.loads(asin_info)
        except:
            return JsonResponse({'code': "ERROR", "message": "ASIN不存在"})

        return JsonResponse(asin_dict)


class KeyWordSearchView(View):

    def get(self, request):
        marketplace = request.GET.get('marketplace') 
        asin_ = request.GET.get("asin")
        asin = AsinSeedApiTest()
        urlStr = asin.main(marketplace, asin_)
        try:
            asin_info = requests.get(urlStr[1]).content
            asin_dict = json.loads(asin_info)
            print(urlStr[1])
        except:
            return JsonResponse({'code': "ERROR", "message": "关键词不存在"})
        try:
            data_all = asin_dict['data']['keywords']
            for i in range(0, len(data_all)):
                search_volume = data_all[i]['search_volume']
                results = data_all[i]['results'] 
                cvr = data_all[i]['cvr']
                try:
                    quality_factor = search_volume * cvr * 0.5 / results * 100
                    data_all[i]['quality'] = quality_factor
                except:
                    quality_factor = 0.00
                    data_all[i]['quality'] = quality_factor
        except:
            return JsonResponse({'code': "ERROR", "message": "请使用关键词搜索"})

        return JsonResponse(asin_dict)



class SaveASINInfo(View):

    def post(self, request):
        asinSearchData = request.POST.get('asinSearchData')  # asin data
        marketplace = request.POST.get('marketplace')  # site
        asin = request.POST.get('asin')  # asin
        json_dict = json.loads(asinSearchData)

        # Verification parameter
        if not all([asinSearchData, marketplace, asin]):
            return JsonResponse({'code': RET.PARAMERR})

        try:
            site_id = Site.objects.create(
                site_name=marketplace 
            )
            asin_id = Asin.objects.create(
                asin_name=asin
            )
        except:
            return JsonResponse({'code': RET.DBERR, 'message': "站点或关键词有误"})
        try:
            # Write to database/写入数据库
            for i in json_dict:
                asin_keyword_id = AsinKeywordInfo.objects.create(
                    search_volume=i['search_volume'], 
                    keywordinfo_name=i['keyword'], 
                    search_hot=i['search_weight'] 
                )
                Asininfo.objects.create(
                    asin=asin_id,
                    asininfo=asin_keyword_id
                )
        except:
            return JsonResponse({'code': RET.DBERR})
        try:
            SiteAsin.objects.create(
                sid=site_id,
                aid=asin_id
            )
        except:
            return JsonResponse({'code': RET.DBERR})

        return JsonResponse({'code': RET.OK})


class SearchKeyWordInfo(View):
    def post(self, request):
        keywordData = request.POST.get('keywordData')  # keyword Data
        marketplace = request.POST.get('marketplace')  # site
        keyword = request.POST.get('keyword')  # keyword
        json_dict = json.loads(keywordData)
        if not all([keywordData, marketplace, keyword]): 
            return JsonResponse({'code': RET.PARAMERR})
        try:
            keyword_site_id = Site.objects.create(
                site_name=marketplace 
            )
            keyword_id = Keyword.objects.create(
                keyword_name=keyword 
            )

        except:
            return JsonResponse({'code': RET.DBERR})
        for i in json_dict:
            keyword_info_id = AsinKeywordInfo.objects.create(
                search_trend=i['search_trend'],
                purchase=i['purchase'],
                search_volume=i['search_volume'],
                keywordinfo_name=i['keyword'],
                results=i['results'],
                cvr=i['cvr'],
                quality=i['quality']
            )

            Keywordinfo.objects.create(
                keyword=keyword_id,
                keywordinfo=keyword_info_id
            )
            try:
                SiteKeyword.objects.create(
                    sid_id=keyword_site_id.id,
                    kid_id=keyword_id.id
                )
            except:
                return JsonResponse({'code': RET.DBERR})
        return JsonResponse({'code': RET.OK})


class KeyWordsSummaryView(APIView):
    def get(self, request):
        page_num = request.GET.get('page')
        queryset = AsinKeywordInfo.objects.all().order_by('update_time')
        serializer_class = KeyWordsSummarySerializer
        page = PageNumberPagination()
        page_list = page.paginate_queryset(queryset, request, view=self)
        ser = serializer_class(instance=page_list, many=True)
        all_data_count = AsinKeywordInfo.objects.all().count()
        paginator = Paginator(queryset, 100)
        total_pages = paginator.num_pages
        return Response(
            {"code": RET.OK, "data": ser.data, 'total_page': total_pages, 'count': all_data_count, 'page': page_num,
             'page_size': REST_FRAMEWORK.get('PAGE_SIZE')})



class KeyWordsAffirmView(APIView):
    def get(self, request):
        category_all = AffirmCategory.objects.all().values()
        return Response({'code': RET.OK, 'cateList': category_all})

    def post(self, request):
        affirm_keywords = request.POST.get('KeyWordList')
        category = request.POST.get("category")
        json_dict = json.loads(affirm_keywords)
        if not all([affirm_keywords, category]):
            return Response({'code': RET.PARAMERR, "message": "缺少参数"})

        category_ = AffirmCategory.objects.create(
            affirmcategoryname=category
        )
        keyword_list = []
        for i in json_dict:
            keyword = i['keyword']
            keyword_list.append(keyword)
        word_list = []
        for words in keyword_list:
            word = words.split()
            for w in word:
                word_list.append(w)
        l1 = []  # Root
        l2 = []  # frequency
        s = set()
        for j in word_list:
            if j not in s:
                s.add(j)
                l1.append(j)
                l2.append(word_list.count(j))
        dict_name = dict(zip(l1, l2))
        for k, v in dict_name.items():
            AffirmWords.objects.create(
                affirmname=k,
                affirmfrequency=v,
                cate_id=category_.id
            )
        for data in json_dict:
            AffirmCi.objects.create(
                affirmkeywordname=data['keyword'],
                affirmsearch_volume=data['MonthSearch'],
                affirmresults=data['CompetingNum'],
                affirmpurchase=data['Purchase'],
                affirmcvr=data['RateOfPurchase'],
                affirmquality=data['Sponsored'],
                affirmqualitygrade=data['QualityLevel'],
                affirm_foreign_id=category_.id
            )

        return Response({'code': RET.OK})

    def put(self, request):
        affirm_keywords = request.POST.get('KeyWordList')
        category = request.POST.get("category")
        json_dict = json.loads(affirm_keywords)
        keyword_list = []
        for i in json_dict:
            keyword = i['keyword']
            keyword_list.append(keyword)
        word_list = []
        for words in keyword_list:
            word = words.split()
            for w in word:
                word_list.append(w)
        l1 = []  # Root
        l2 = []  # frequency
        s = set()
        for j in word_list:
            if j not in s:
                s.add(j)
                l1.append(j)
                l2.append(word_list.count(j))
        dict_name = dict(zip(l1, l2))
        for k, v in dict_name.items():
            AffirmWords.objects.update_or_create(
                affirmname=k,
                affirmfrequency=v,
                cate_id=category
            )
        for data in json_dict:
            AffirmCi.objects.filter(affirm_foreign_id=category).update_or_create(
                affirmkeywordname=data['keyword'],
                affirmsearch_volume=data['MonthSearch'],
                affirmresults=data['CompetingNum'],
                affirmpurchase=data['Purchase'],
                affirmcvr=data['RateOfPurchase'],
                affirmquality=data['Sponsored'],
                affirmqualitygrade=data['QualityLevel'],
                affirm_foreign_id=category
            )

        return Response({'code': RET.OK})

    def delete(self, request):
        keywordList = request.POST.get('keywordList')
        json_dict = json.loads(keywordList)
        for i in json_dict:
            AsinKeywordInfo.objects.filter(id=i).delete()
            Keywordinfo.objects.filter(keywordinfo=i).delete()
        return Response({
            'code': RET.OK
        })


class KeyWordsNegativeView(APIView):
    """
    python ../manage.py inspectdb > uj_search/models.py
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    python manage.py runserver 0.0.0.0:8888
    """

    def post(self, request):
        negative_affirm_keywords = request.POST.get('KeyWordList')
        category = request.POST.get("category")
        json_dict = json.loads(negative_affirm_keywords)
        if not all([negative_affirm_keywords, category]):
            return Response({'code': RET.PARAMERR, "message": "缺少参数"})
        negative_category_ = AffirmCategory.objects.create(
            negativecategoryname=category
        )
        negative_keyword_list = []
        for i in json_dict:
            keyword = i['keyword']
            negative_keyword_list.append(keyword)
        word_list = []
        for words in negative_keyword_list:
            word = words.split()
            for w in word:
                word_list.append(w)
        negative_l1 = []  # Root
        negative_l2 = []  # frequency
        s = set()
        for j in word_list:
            if j not in s:
                s.add(j)
                negative_l1.append(j)
                negative_l2.append(word_list.count(j))

        dict_name = dict(zip(negative_l1, negative_l2))
        for k, v in dict_name.items():
            NegativeWords.objects.create(
                negativename=k,
                negativefrequency=v,
                negative_cate_id=negative_category_.id
            )

        for data in json_dict:
            NegativeCi.objects.create(
                negativekeywordname=data['keyword'],
                negativesearchvolume=data['search_volume'],
                negative_foreign_id=negative_category_.id
            )
        return Response({'code': RET.OK})

    def put(self, request):
        affirm_keywords = request.POST.get('KeyWordList')
        category = request.POST.get("category")
        json_dict = json.loads(affirm_keywords)
        negative_keyword_list = []
        for i in json_dict:
            keyword = i['keyword']
            negative_keyword_list.append(keyword)
        word_list = []
        for words in negative_keyword_list:
            word = words.split()
            for w in word:
                word_list.append(w)
        negative_l1 = []  # Root
        negative_l2 = []  # frequency
        s = set()
        for j in word_list:
            if j not in s:
                s.add(j)
                negative_l1.append(j)
                negative_l2.append(word_list.count(j))

        dict_name = dict(zip(negative_l1, negative_l2))
        for k, v in dict_name.items():
            NegativeWords.objects.update_or_create(
                negativename=k,
                negativefrequency=v,
                negative_cate_id=category
            )

        for data in json_dict:
            NegativeCi.objects.filter(negative_foreign_id=category).update_or_create(
                negativekeywordname=data['keyword'],
                negativesearchvolume=data['search_volume'],
                negative_foreign_id=category
            )

        return Response({'code': RET.OK})

    # def delete(self, request):
    #     keywordList = request.POST.get('keywordList')
    #     json_dict = json.loads(keywordList)
    #     for i in json_dict:
    #         AsinKeywordInfo.objects.filter(id=i).delete()
    #         Keywordinfo.objects.filter(keywordinfo=i).delete()
    #     return Response({
    #         'code': RET.OK
    #     })

class AffirmInfoView(APIView):
    def get(self, request):
        cate_id = request.GET.get('cate_id')
        page_num = request.GET.get('page_num')
        if not cate_id or page_num:
            page_num = request.GET.get('page')
            queryset = AffirmCi.objects.all().order_by('update_time')
            serializer_class = AffirmSummarySerializer
            page = PageNumberPagination()
            page_list = page.paginate_queryset(queryset, request, view=self)
            ser = serializer_class(instance=page_list, many=True)
            paginator = Paginator(queryset, 100)
            all_data_count = AffirmCi.objects.all().count()
            total_pages = paginator.num_pages
            # words = AffirmWords.objects.all().values()
            category = AffirmCategory.objects.all().values()
            return Response(
                {'code': RET.OK, "data": ser.data, 'total_page': total_pages, 'page': page_num,
                 "count": all_data_count, 'page_size': REST_FRAMEWORK.get('PAGE_SIZE'), "cateList": category})

        queryset = AffirmCi.objects.filter(affirm_foreign_id=cate_id).order_by('update_time')
        serializer_class = AffirmSummarySerializer
        page = PageNumberPagination()
        page_list = page.paginate_queryset(queryset, request, view=self)
        ser = serializer_class(instance=page_list, many=True)
        paginator = Paginator(queryset, 100)
        all_data_count = AffirmCi.objects.all().count()
        total_pages = paginator.num_pages
        words = AffirmWords.objects.filter(cate_id=cate_id).all().values().order_by('-affirmfrequency')
        category = AffirmCategory.objects.all().values()
        return Response(
            {'code': RET.OK, "data": ser.data, 'total_page': total_pages, 'page': page_num, "frequency": words,
             "count": all_data_count, 'page_size': REST_FRAMEWORK.get('PAGE_SIZE'), "cateList": category})

    def delete(self, request):
        cate_id = request.POST.get('cate_id')
        keywordList = request.POST.get('keywordList')
        json_dict = json.loads(keywordList)
        for i in json_dict:
            AffirmCi.objects.filter(affirm_foreign_id=cate_id).filter(id=i).delete()
        return Response({
            'code': RET.OK
        })


class NegativeInfoView(APIView):
    def get(self, request):
        cate_id = request.GET.get('cate_id')
        page_num = request.GET.get('page_num')
        if not cate_id or page_num:
            page_num = request.GET.get('page')
            queryset = NegativeCi.objects.all().order_by('update_time')
            serializer_class = NegativeSummarySerializer
            page = PageNumberPagination()
            page_list = page.paginate_queryset(queryset, request, view=self)
            ser = serializer_class(instance=page_list, many=True)
            paginator = Paginator(queryset, 100)
            all_data_count = NegativeCi.objects.all().count()
            total_pages = paginator.num_pages
            # words = NegativeWords.objects.all().values() "frequency": words,
            category = AffirmCategory.objects.all().values()
            return Response(
                {'code': RET.OK, "data": ser.data, 'total_page': total_pages, 'page': page_num,
                 "count": all_data_count, 'page_size': REST_FRAMEWORK.get('PAGE_SIZE'), "cateList": category})

        queryset = NegativeCi.objects.filter(negative_foreign_id=cate_id).order_by('update_time')
        serializer_class = NegativeSummarySerializer
        page = PageNumberPagination()
        page_list = page.paginate_queryset(queryset, request, view=self)
        ser = serializer_class(instance=page_list, many=True)
        paginator = Paginator(queryset, 100)
        all_data_count = NegativeCi.objects.all().count()
        total_pages = paginator.num_pages
        words = NegativeWords.objects.filter(negative_cate_id=cate_id).all().values().order_by('-negativefrequency')
        category = AffirmCategory.objects.all().values()
        return Response(
            {'code': RET.OK, "data": ser.data, 'total_page': total_pages, 'page': page_num, "frequency": words,
             "count": all_data_count, 'page_size': REST_FRAMEWORK.get('PAGE_SIZE'), "cateList": category})

    def delete(self, request):
        cate_id = request.POST.get('cate_id')
        keywordList = request.POST.get('keywordList')
        json_dict = json.loads(keywordList)
        for i in json_dict:
            NegativeCi.objects.filter(negative_foreign_id=cate_id).filter(id=i).delete()

        return Response({
            'code': RET.OK
        })


class PositiveWordMatrixView(APIView):
    def get(self, request):
        category_all = AffirmCategory.objects.all().values()  # category
        # positive_word = request.GET.get('positive_word')
        positive_word = AffirmWords.objects.all().values()
        info_list = []
        for i in positive_word:
            info = {
                'affirmName': i.get('affirmname'),
                'affirmFrequency': i.get('affirmfrequency')
            }
            info_list.append(info)
        return Response({'code': RET.OK, 'cateList': category_all, 'data': info_list})


class NegativeWordMatrixView(APIView):
    pass

你可能感兴趣的:(不写注释的程序员)