Spaces:
Sleeping
Sleeping
File size: 7,817 Bytes
0bd6e09 f87b88a 0bd6e09 f87b88a 0bd6e09 3fcef8d 0bd6e09 f87b88a 0bd6e09 f87b88a 0bd6e09 f87b88a 0bd6e09 f87b88a 0bd6e09 f87b88a 0bd6e09 f87b88a 0bd6e09 f87b88a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.decorators import api_view
import json
from .models import Products, Categories
import os
import requests
from django.http import HttpResponse
from django.template import loader
from concurrent.futures import ThreadPoolExecutor
# Create your views here.
@api_view(['GET'])
def getProductData(request, category):
page = request.GET.get('page')
obj = Products.objects.filter(category=Categories.objects.filter(link=category).first()).all()
data = {"data": []}
for i in obj:
temp = {}
temp["name"] = i.name
temp["score"] = i.score
temp["image"] = i.image
temp["propGroups"] = i.propGroupsMini
temp["propScore"] = i.propScore
temp["link"] = i.link
data["data"].append(temp)
data["data"] = sorted(data["data"], key=lambda k: k['score'] if k['score'] is not None else 0, reverse=True)
if page != None:
start = (int(page)-1)*50
end = int(page)*50
data["data"] = data["data"][start:end]
else:
data["data"] = data["data"][:50]
if data["data"] == []:
return Response({"msg": "No Data Found"})
return Response(data)
@api_view(['GET'])
def searchQuery(request):
query = request.GET.get('query')
obj = Products.objects.filter(name__contains=query).all()
data = {"data": []}
for i in obj:
temp = {}
temp["name"] = i.name
temp["score"] = i.score
temp["image"] = i.image
temp["propGroups"] = i.propGroupsMini
temp["propScore"] = i.propScore
temp["link"] = i.link
data["data"].append(temp)
return Response(data)
@api_view(['GET'])
def fetchCategory(request):
obj = Categories.objects.all()
data = {"data": []}
for i in obj:
temp = {}
temp["name"] = i.name
temp["link"] = i.link
data["data"].append(temp)
return Response(data)
@api_view(['GET'])
def comparisionData(request):
try:
compare = request.GET.get('compare')
url = "https://versus.com/api/store/en/"+compare+"?ts=9980526090123&userId=&type=json"
response = requests.request("GET", url)
return HttpResponse(json.dumps(response.json()), content_type="application/json")
except:
return Response({"error": "No Data Found"})
@api_view(['GET'])
def fetchPriceData(request):
try:
compare = request.GET.get('compare')
url = "https://versus.com/api/prices/"+compare+"/IN?type=json"
headers = {
'Accept': 'application/json'
}
response = requests.request("GET", url, headers=headers)
return HttpResponse(json.dumps(response.json()), content_type="application/json")
except:
return Response({"error": "No Data Found"})
# path = "./data/"
# dir_list = os.listdir(path)
# print(dir_list)
# for path in dir_list:
# f = open('./data/'+path, "r")
# data = json.loads(f.read())
# for i in data["data"]:
# try:
# obj = Products(name=i["name"], score=i["score"], image=i["image"],
# propGroups=i["propGroups"], propScore=i["propScore"], category=path.split(".json")[0].replace("-", " "))
# obj.save()
# except:
# pass
# print(path)
# path = "./data/"
# dir_list = os.listdir(path)
# print(dir_list)
# for path in dir_list:
# obj = Categories(name=path.split(".json")[0].replace("-", " ").title())
# obj.save()
# print(path)
def getComparisonChart(request):
compare = request.GET.get('compare')
url = "https://versus.com/share/summary/en/"+compare
response = requests.get(url)
template ="<!doctype html><html lang='en' data-reactroot=''><head><link href='/static/chart/chartStyle.css' media='all' rel='stylesheet' type='text/css' /><script type='module' src='/static/chart/chartScript1.mjs'></script><script type='module' src='/static/chart/chartScript2.mjs'></script><script type='module' src='/static/chart/chartScript3.mjs'></script></head><body style='margin:0;min-height:100%;position:relative;font-family:-apple-system,BlinkMacSystemFont,Roboto,Oxygen,Ubuntu,Cantarell,sans-serif'><div id='root'></div><script id='reactInitData'>window.__data = '%%INITIAL_DATA%%';</script><script type='text/javascript'>(function() {var check = document.createElement('script');if (!('noModule' in check) && 'onbeforeload' in check) {var support = false;document.addEventListener('beforeload', function(e) {if (e.target === check) {support = true;} else if (!e.target.hasAttribute('nomodule') || !support) {return;}e.preventDefault();}, true);check.type = 'module';check.src = '.';document.head.appendChild(check);check.remove();}}());</script></body></html>"
data = (response.text)
data = data.split("<script id=\"reactInitData\">window.__data=")[1].split("</script>")[0]
template = template.replace("'%%INITIAL_DATA%%'", data)
return HttpResponse(template)
def dataManipulator(request):
# list all files from ./data/
path = "./data/"
dir_list = os.listdir(path)
categorys = Categories.objects.all()
count = 0
for i in dir_list:
products = Products.objects.filter(category=categorys[count]).all()
count += 1
data = json.loads(open(path+i, "r").read())
for product in products:
for j in data["data"]:
if j["name"] == product.name:
print(product.name)
product.propGroupsMini = j["propGroups"]
Products.objects.bulk_update(products, ["propGroupsMini"])
return HttpResponse("Done")
def threadFunc(product,count):
if product.terms == {}:
try:
url = "https://versus.com/api/store/en/"+product.link+"?ts=9980526090123&userId=&type=json"
response = requests.request("GET", url)
data = response.json()
product.terms = data["terms"]
product.suggestions = data["searchOverlay"]["suggestions"]
product.tldr = data["comparison"]["tldr"][0]
product.propGroups = data["comparison"]["propGroups"]
product.notApplicableProps = data["comparison"]["notApplicableProps"]
product.cheapAlternatives = data["comparison"]["cheapAlternatives"]
product.topProps = data["comparison"]["topProps"]
product.popularCompare = data["comparison"]["popular"]
product.toplist = data["comparison"]["toplist"]
print(count," : ",product.name)
except:
print("Error : ",product.name)
else:
print("Already Done : ",product.name)
import threading
def dataAdder(request):
products = Products.objects.order_by("name").all()
count = 0
for i in range(0,len(products),5):
count += 1
t1 = threading.Thread(target=threadFunc, args=(products[i],count))
count += 1
t2 = threading.Thread(target=threadFunc, args=(products[i+1],count))
count += 1
t3 = threading.Thread(target=threadFunc, args=(products[i+2],count))
count += 1
t4 = threading.Thread(target=threadFunc, args=(products[i+3],count))
count += 1
t5 = threading.Thread(target=threadFunc, args=(products[i+4],count))
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()
t1.join()
t2.join()
t3.join()
t4.join()
t5.join()
if count > 14400:
products[i].save()
products[i+1].save()
products[i+2].save()
products[i+3].save()
products[i+4].save()
return HttpResponse("Done") |