Spaces:
Sleeping
Sleeping
| from django.shortcuts import render | |
| from rest_framework.response import Response | |
| from rest_framework.decorators import api_view | |
| import http.client | |
| import json | |
| import requests | |
| from bs4 import BeautifulSoup | |
| # Create your views here. | |
| def sessionIdGenrator(): | |
| conn = http.client.HTTPSConnection("www.amazon.in") | |
| payload = '' | |
| headers = {} | |
| conn.request("GET", "/", payload, headers) | |
| res = conn.getresponse() | |
| data = res.read() | |
| response = data.decode("utf-8") | |
| ue_sid = response.split("ue_sid =")[1].split(',')[0].split("'")[1] | |
| ue_mid = response.split("ue_mid =")[1].split(',')[0].split("'")[1] | |
| return ue_sid, ue_mid | |
| def searchAPI(query): | |
| conn = http.client.HTTPSConnection("2.rome.api.flipkart.com") | |
| payload = json.dumps({ | |
| "query": query, | |
| "marketPlaceId": "FLIPKART", | |
| "types": [ | |
| "QUERY", | |
| "QUERY_STORE", | |
| "PRODUCT", | |
| "RICH", | |
| "PARTITION" | |
| ], | |
| "rows": 10 | |
| }) | |
| headers = { | |
| 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36', | |
| 'X-User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 FKUA/website/42/website/Desktop', | |
| 'Content-Type': 'application/json' | |
| } | |
| conn.request("POST", "/api/4/discover/autosuggest", payload, headers) | |
| res = conn.getresponse() | |
| data = res.read() | |
| response = data.decode("utf-8") | |
| return json.loads(response) | |
| def getAllProduct(query, page): | |
| url = "https://2.rome.api.flipkart.com/api/4/page/fetch" | |
| payload = json.dumps({"pageUri":"/search?q="+query+"&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off","pageContext":{"fetchSeoData":True,"paginatedFetch":False,"pageNumber":page},"requestContext":{"type":"BROWSE_PAGE"}}) | |
| headers = { | |
| 'Accept': '*/*', | |
| 'Accept-Language': 'en-US,en;q=0.9,gu;q=0.8', | |
| 'Connection': 'keep-alive', | |
| 'Content-Type': 'application/json', | |
| 'Origin': 'https://www.flipkart.com', | |
| 'X-User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 FKUA/website/42/website/Desktop' | |
| } | |
| data=[] | |
| response = requests.request("POST", url, headers=headers, data=payload) | |
| slots = response.json()["RESPONSE"]["slots"] | |
| for slot in slots: | |
| if slot["slotType"] == "WIDGET": | |
| if slot["widget"]["type"] == "PRODUCT_SUMMARY": | |
| temp = {} | |
| try: | |
| title = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["titles"]["title"] | |
| temp["title"] = title | |
| except: | |
| pass | |
| try: | |
| link = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["smartUrl"] | |
| temp["link"] = link | |
| except: | |
| pass | |
| try: | |
| keySpecs = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["keySpecs"] | |
| temp["keySpecs"] = keySpecs | |
| except: | |
| pass | |
| try: | |
| minKeySpecs= slot["widget"]["data"]["products"][0]["productInfo"]["value"]["minKeySpecs"] | |
| temp["minKeySpecs"] = minKeySpecs | |
| except: | |
| pass | |
| media = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["media"]["images"] | |
| images = [] | |
| for i in media: | |
| images.append(i["url"].replace("{@width}", "1000").replace("{@height}", "1000").replace("{@quality}", "100")) | |
| try: | |
| temp["imgs"] = images | |
| except: | |
| pass | |
| try: | |
| price = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["pricing"]["finalPrice"]["value"] | |
| temp["price"] = price | |
| except: | |
| pass | |
| try: | |
| fullPrice = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["pricing"]["mrp"]["value"] | |
| temp["fullPrice"] = fullPrice | |
| except: | |
| pass | |
| try: | |
| symbol = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["pricing"]["mrp"]["currency"] | |
| if symbol == "INR": | |
| symbol = "₹" | |
| if symbol == "USD": | |
| symbol = "$" | |
| if symbol == "EUR": | |
| symbol = "€" | |
| if symbol == "GBP": | |
| symbol = "£" | |
| if symbol == "AUD": | |
| symbol = "A$" | |
| temp["symbol"] = symbol | |
| except: | |
| pass | |
| try: | |
| stars = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["rating"]["average"] | |
| temp["stars"] = str(stars)+ " out of 5 stars" | |
| except: | |
| pass | |
| try: | |
| starCount = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["rating"]["roundOffCount"] | |
| temp["starCount"] = starCount | |
| except: | |
| pass | |
| try: | |
| reviews = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["rating"]["reviewCount"] | |
| temp["reviews"] = reviews | |
| except: | |
| pass | |
| try: | |
| offer = "" | |
| for i in slot["widget"]["data"]["products"][0]["snippets"]: | |
| for j in i["data"]: | |
| offer = offer + j["value"]["text"] | |
| offer = offer + ", " | |
| offer = offer[:-2] | |
| temp["offer"] = offer | |
| except: | |
| pass | |
| data.append(temp) | |
| return data | |
| def getProductsList(request): | |
| query = (request.GET.get('query')).replace(" ", "+") | |
| try: | |
| page = (request.GET.get('page')) | |
| except: | |
| page = 1 | |
| if page == None: | |
| page = 1 | |
| data = getAllProduct(query, page) | |
| return Response({"data": data}) | |
| def getProductDetail(request): | |
| productId = request.GET.get('id') | |
| conn = http.client.HTTPSConnection("www.amazon.in") | |
| payload = '' | |
| headers = {} | |
| conn.request("GET", "/dp/"+productId+"/", payload, headers) | |
| res = conn.getresponse() | |
| data = res.read() | |
| response = data.decode("utf-8") | |
| data = {} | |
| soup = BeautifulSoup(response, features="html5lib") | |
| #title = response.split('id="productTitle"')[1].split(">")[1].split("</span")[0].strip() | |
| title = soup.find_all( | |
| "span", {"class", "a-size-large product-title-word-break"})[0].text.strip() | |
| data['title'] = title | |
| symbol = soup.find_all("span", {"class", "a-price-symbol"})[0].text | |
| data["symbol"] = symbol | |
| savingsPercentage = soup.find_all( | |
| "span", {"class", "savingsPercentage"})[0].text | |
| data["savingPercentage"] = savingsPercentage | |
| imgs = soup.find_all( | |
| "img", {"class", "a-dynamic-image"}) | |
| imgArr = [] | |
| for i in imgs: | |
| imgArr.append("https://m.media-amazon.com/images/I/" + | |
| i["src"].split("/I/")[1].split(".")[0]+".jpg") | |
| data["images"] = imgArr | |
| scripts = soup.find_all("script") | |
| tempData = {} | |
| for i in scripts: | |
| try: | |
| temp = str(i).split("<script")[1].split( | |
| ">")[1].split("</script")[0] | |
| for key, item in json.loads(temp).items(): | |
| if item != None or item != "nulll" or item != True or item != False: | |
| tempData[key] = item | |
| except: | |
| pass | |
| data["currencyCode"] = tempData["currencyCode"] | |
| data["productPrice"] = tempData["productPrice"] | |
| data["brand"] = tempData["brand"] | |
| data["category"] = tempData["buyBackCategory"] | |
| return Response({"data": data}) | |
| def searchQuery(request): | |
| query = request.GET.get('query') | |
| tempData = searchAPI(query) | |
| values = [] | |
| for i in tempData["RESPONSE"]["suggestions"]: | |
| try: | |
| temp = {} | |
| temp["title"] = i["data"]["component"]["value"]["title"] | |
| temp["imageUrl"] = i["data"]["component"]["value"]["imageUrl"].replace( | |
| "{@width}", "1080").replace("{@height}", "1080").replace("{@quality}", "100") | |
| values.append(temp) | |
| except: | |
| pass | |
| data = {"data": values} | |
| return Response(data) | |