Answer the question
In order to leave comments, you need to log in
How to get rid of global variable in views.py file?
The task is to get a list of cities from the VK API by country ID. Then you need to make a button to sort the cities in alphabetical order. Here is how I implemented it:
def get_cities(request, id):
global cities_list
METHOD = 'database.getCities'
response = requests.get(
f'{URL}{METHOD}?access_token={TOKEN}&v={VK_API}&country_id={id}'
)
content = response.json()
cities_list = [i['title'] for i in content['response']['items']]
context = {'cities': cities_list}
return render(request, 'countries/cities_list.html', context)
def sort_cities(request):
cities_list.sort(key=lambda x: x[0])
context = {'cities': cities_list}
return render(request, 'countries/cities_list.html', context)
Answer the question
In order to leave comments, you need to log in
@lru_cache
def get_cities(id):
METHOD = 'database.getCities'
response = requests.get(
f'{URL}{METHOD}?access_token={TOKEN}&v={VK_API}&country_id={id}'
)
content = response.json()
return [i['title'] for i in content['response']['items']]
def show_cities(request, id, ordered=False):
cities_list = get_cities(id)
if ordered:
cities_list = sorted(cities_list, key=lambda x: x[0])
return render(request, 'countries/cities_list.html', {'cities': cities_list})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question