# -*- coding: utf-8 -*- import random from django.db import connection def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip def get_by_sort(banner_list): max_sort = 0 for banner in banner_list: sort = banner.sort if sort > max_sort: max_sort = sort result = [banner for banner in banner_list if banner.sort == max_sort] return result def get_banner_by_params(banners_list, urls, params): thematic_banners = [] url_banners = [] for banner in banners_list: # check by theme banner_theme_ids = [str(theme.id) for theme in banner.theme.all()] if banner_theme_ids: if params.get('theme'): theme = params['theme'] flag = False for th in theme: if th in banner_theme_ids: flag = True if flag: thematic_banners.append(banner) continue # check by country banner_country_ids = [str(country.id) for country in banner.country.all()] #print('number of queries = %d'%len(connection.queries)) if banner_country_ids: if params.get('country'): country = params['country'] if country in banner_country_ids: thematic_banners.append(banner) continue # check by url if urls: banner_urls = banner.urls.all() print('number of queries = %d'%len(connection.queries)) if banner_urls: banner_urls = set(banner_urls) common_urls = set(urls).intersection(banner_urls) if common_urls: url_banners.append(banner) continue if thematic_banners: return random.choice(thematic_banners) if url_banners: return random.choice(url_banners) return None #print('END. NUMBER of queries = %d'%len(connection.queries)) def get_top_events(tops, params): catalog = params.get('catalog') country = params.get('country', '') theme = params.get('theme', []) city = params.get('city', '') tag = params.get('tag', '') catalog_tops = [item for item in tops if item.catalog == catalog] good_tops = [] for top in catalog_tops: country_ids = [str(item.id) for item in top.country.all()] theme_ids = [str(item.id) for item in top.theme.all()] excluded_tags_ids = [str(item.id) for item in top.excluded_tags.all()] excluded_cities_ids = [str(item.id) for item in top.excluded_cities.all()] if not country_ids and not theme_ids: # universal top good_tops.append(top) continue # check country if country in country_ids and city not in excluded_cities_ids : good_tops.append(top) continue # check theme if tag in excluded_tags_ids: continue flag = False for th in theme: if th in theme_ids: flag = True continue if flag: good_tops.append(top) sorted_top = sorted(good_tops, key=lambda x: x.position) events = [] for top in sorted_top: event = top.get_event() if event: events.append(event) return events