/
views.py
77 lines (55 loc) 路 2.21 KB
/
views.py
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
import logging
import time
import hashlib
from django.shortcuts import render
from find_books.integrations import Amazon, Flipkart, Infibeam, BooksMela ,Snapdeal,Bookswagon
_LOGGER = logging.getLogger(__name__)
def validate_price(items=[]):
""" This function checks a list of items and returns a validated list with items who have float price only.
Args:
items (list): a list of dictionaries.
Returns:
list: returns a list of dictionaries with float not none price key.
"""
validated = []
for item in items:
if not item['price'] == None and isinstance(item['price'], float):
validated.append(item)
return validated
def index(request):
"""View function for the home page of site.
Args:
request: the request we recive from the user.
Returns:
A render object that was rendered with 'find_books/index.html' template
"""
#Renders the HTML template find_books/index.html.
return render(request, 'find_books/index.html')
def search(request):
"""View function for the results.html page.
Args:
request: the request we recive from the user.
Returns:
A render object that was rendered with 'find_books/results.html' template and context.
"""
start = time.time()
query = request.GET.get('q')
threads = [Amazon(query), Flipkart(query), Infibeam(query), BooksMela(query), Snapdeal(query),Bookswagon(query)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
all_items = []
relevant = []
for thread in threads:
items = validate_price(thread.items)
if items:
for item in items:
item['hash'] = hashlib.md5(item['link'].encode('utf-8')).hexdigest()
all_items.extend(items)
relevant.extend(items[:2])
all_items = sorted(all_items, key=lambda k: k['price'])
relevant = sorted(relevant, key=lambda k: k['price'])
all_items = [x for x in all_items if x not in relevant]
_LOGGER.debug("Query: (" + query + ") took (" + str(time.time() - start) + ") secs")
return render(request, 'find_books/results.html', {'all': all_items, 'relevant': relevant, 'query': query})