Y
Y
YuriyCherniy2019-10-25 11:56:13
Django
YuriyCherniy, 2019-10-25 11:56:13

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)

In order not to access the API for the same information in different functions, I made the cities_list variable global, which, in my opinion, is not very good. How to solve this problem without a global variable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-10-25
@YuriyCherniy

@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 question

Ask a Question

731 491 924 answers to any question