Как получить доступ к результатам потоков и отобразить их в шаблоне
У меня есть основное представление, которое отображает города и цены на авиабилеты. Функция веб-скрепера, которая получает цены на рейсы, занимает некоторое время, поэтому вместо того, чтобы располагать ее в моем основном представлении, я создал для нее отдельную функцию. Эта функция запускается async при загрузке основного представления, однако мне интересно, как я могу передать данные prices_list из моей функции в основное представление, чтобы они отображались в шаблоне. Я новичок в Django и потоках, поэтому буду очень признателен за любую помощь!
views.py
def results(request):
# user city
user_city = "Madrid"
# create list of cities
city_list = ["Toronto", "Montreal", "Calgary", "Edmonton", "Vancouver", "Quebec"]
t = threading.Thread(target=get_prices, args=[city_list, user_city], daemon=True)
t.start()
# change string dictionary into actual dictionary
specific_variable_dictionary = ast.literal_eval(specific_variable_dictionary)
context = {
"user_city": user_city,
}
return render(request, 'Discovery_App/results.html', context)
def get_prices(city_list, user_city):
# create price list
prices_list = []
# set origin for flight
origin = user_city
# set headers
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36"
}
for i in city_list:
# set destination for flight
destination = i
# set search query
url = "https://google.com/search?q=" + origin + " to " + destination + " Google Flights"
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'lxml')
# get price element
prices = soup.find("span", attrs={"class": "GARawf"})
if prices != None:
prices_list.append(prices.text.strip())
else:
prices_list.append("Not Available")