# -*- coding: utf-8 -*- import re import urllib.request, urllib.parse, urllib.error import os from django.http import HttpResponseNotFound from django.http import Http404 from django.urls import reverse from django.conf import settings from django.shortcuts import render from main.models import * from main.util import prepare_text import main.catalogs as catalogs from django.http import JsonResponse #from special_projects.models import SpecProject #from redis_metrics.models import R # для общёта количества просмотров IMAGE_RE = re.compile(r']+src\=\"(.*)\"[^>]+\>') from main.catalogs import category_to_context from main.context_instance import * # контекстные процессоры, самое читаемое, рекомендуемое, реклама def index(request): context = {"URI": urllib.parse.quote(request.get_full_path())} matching_objects = Page.objects.filter(slug="index", site__id=settings.SITE_ID) if not len(matching_objects): raise Http404 obj = matching_objects[0] context = prepare_context(context) context = prepare_context_for_std_object(context, obj) context["show_comments"] = False return render(request, "index.html", context) def format_date(date_obj): if date_obj is not None: # stupid strftime not works with years < 1900 tmp_date = date(2000, date_obj.month, date_obj.day) return "%s.%s" % (tmp_date.strftime("%d.%m"), date_obj.year) else: return None def prepare_date(date_full, date_year=""): return (format_date(date_full) if date_full else date_year) def prepare_connected_object(obj, gender=None): if gender is not None: if gender == "f": obj_teaser = obj.name_female else: obj_teaser = obj.name_male else: if isinstance(obj, BelcantoSubModel): obj_teaser = obj.name elif isinstance(obj, BelcantoModel): obj_teaser = obj.connected_title() elif obj is None: obj_teaser = None else: obj_teaser = str(obj) if os.environ['DJANGO_SPLIT_SETTINGS_MODULE'] != 'ON': if obj is not None and not site_is_current(obj): obj_teaser += " (%s)" % obj.site.all()[0].domain if hasattr(obj, "get_absolute_url"): return '%s' % (obj.get_absolute_url(), obj_teaser) else: return obj_teaser def format_mtm_field(data, lower=True, gender=None): result = ", ".join([prepare_connected_object(d, gender) for d in data.all()]) if result and lower: result = result[0] + result[1:].lower() return result def annotate_with_site(objects): result = [] for obj in objects: if not site_is_current(obj): result.append({"obj": obj, "site": " (%s)" % obj.site.all()[0].domain}) else: result.append({"obj": obj, "site": ""}) return result def prepare_context(context): infodata_connected = context.get("infodata_connected", None) if infodata_connected is not None: new_ic = [] for (k, v) in infodata_connected: new_ic.append((k, annotate_with_site(v))) context["infodata_connected"] = new_ic return context def prepare_context_for_std_object(context, obj): if hasattr(obj, 'get_category'): context["category_obj"] = obj.get_category() if isinstance(obj, Publication): # TODO: заменить случайные новости популярными и релевантными соответственно # десять популярных в данной категории context["by_relevancy_list"] = Publication.get_popular(10) # два релевантных в данной категории context["highly_relevant_list"] = Publication.get_relevant(2) else: print(('&' * 100, 'not isinstance(obj, Publication)')) try: context["by_relevancy_list"] = obj.get_all().order_by('?')[:10] context["highly_relevant_list"] = obj.get_all().order_by('?')[:2] except: print("Not an integer! Please try again.") context["show_comments"] = hasattr(obj, 'type') # проверяю если у объекта тип (PublicationType), если нет - отключаю коменты if hasattr(obj, 'generate_page_title'): context["title"] = obj.generate_page_title() if hasattr(obj, 'get_title'): context["header"] = obj.get_title() if hasattr(obj, 'body'): context["body"] = prepare_text(obj.body) context["links"] = prepare_text(getattr(obj, "links", "")) context["audio_links"] = prepare_text(getattr(obj, "audio_links", "")) context["adv"] = prepare_text(getattr(obj, "adv", "")) context["source"] = getattr(obj, "source", "") context["source_url"] = getattr(obj, "source_url", "") if hasattr(obj, 'images'): images = obj.images.all() context["images"] = images[1:] if len(images) > 0: context["main_image"] = images[0] context["images_count"] = len(images) context["obj"] = obj # ! Здесь контекст боди строчка, и он есть! try: context["admin_url"] = reverse("admin:main_%s_change" % obj._meta.module_name, args=(obj.id,)) except: print("Not an integer! Please try again.") return context def person(request, context, page_id): """персоны""" matching_objects = Person.get_all().filter(slug=page_id) if not len(matching_objects): return None obj = matching_objects[0] context = prepare_context_for_std_object(context, obj) #context['category_name'] = Person. voice_type = format_mtm_field(obj.voice_type) if isinstance(voice_type, str): voice_type = voice_type.lower() context["infodata"] = [ ("Дата рождения", prepare_date(obj.date, obj.year_one)), ("Дата смерти", prepare_date(obj.date_death, obj.year_two)), ("Профессия", format_mtm_field(obj.profession, True, obj.gender)), ("Тип голоса", voice_type), ("Страна", format_mtm_field(obj.countrys, lower=False)) ] context["infodata_connected"] = [ ("Произведения", obj.composition_set.filter(published=True)), ("Публикации", obj.publication_set.filter(published=True)), ("Книги", obj.book_set.filter(published=True)), ("Главы из книг", obj.bookchapter_set.filter(published=True)), ("Словарные статьи", obj.terms.filter(published=True)), ("Записи", obj.as_composer_music_pages.filter(published=True)), ("Записи", obj.as_musician_music_pages.filter(published=True)), ] context["model_slug"] = "persons" context["objects_name"] = "Персоналии" return render(request, "content_article.html", prepare_context(context)) def publication(request, context, page_id): """Новость""" matching_objects = Publication.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None obj = matching_objects[0] context = prepare_context_for_std_object(context, obj) if settings.SITE_ID == 3: #operanews context["infodata"] = [] else: context["infodata"] = [("Тип", format_mtm_field(obj.type))] context["infodata"] += [ ("Раздел", format_mtm_field(obj.category)), ("Театры и фестивали", format_mtm_field(obj.places, lower=False)), ("Персоналии", format_mtm_field(obj.persons, lower=False)), ("Коллективы", format_mtm_field(obj.collectives, lower=False)), ("Произведения", format_mtm_field(obj.compositions, lower=False)), ("Словарные статьи", format_mtm_field(obj.terms, lower=True)), ] context["tags"] = [] for (_, t) in context["infodata"]: if t: context["tags"].append(t) context["model_slug"] = "news" context["objects_name"] = "Новости" return render(request, "news_post.html", prepare_context(context)) def composition(request, context, page_id): """Произведение""" matching_objects = Composition.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None obj = matching_objects[0] context = prepare_context_for_std_object(context, obj) context["infodata"] = [ ("Композитор", prepare_connected_object(obj.composer)), ("Год создания", obj.year), ("Дата премьеры", format_date(obj.date)), ("Жанр", format_mtm_field(obj.genre)), ("Страна", format_mtm_field(obj.countrys, lower=False)), ] context["infodata_connected"] = [ ("Записи", obj.records.filter(published=True)), ("Публикации", obj.publication_set.filter(published=True)), ("Книги", obj.book_set.filter(published=True)), ("Главы из книг", obj.bookchapter_set.filter(published=True)), ("Словарные статьи", obj.terms.filter(published=True)), ] context["model_slug"] = "compositions" context["objects_name"] = "Произведения" return render(request, "content_article.html", prepare_context(context)) def place(request, context, page_id): """Места""" matching_objects = Place.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None obj = matching_objects[0] context = prepare_context_for_std_object(context, obj) context["infodata"] = [ ("Город", prepare_connected_object(obj.city)), ("Год основания", obj.year), ("Тип", format_mtm_field(obj.types)), ] context["infodata_connected"] = [ ("Публикации", obj.publication_set.filter(published=True)), ("Книги", obj.book_set.filter(published=True)), ("Главы из книг", obj.bookchapter_set.filter(published=True)), ("Словарные статьи", obj.terms.filter(published=True)) ] types = obj.types.all() return render(request, "content_article.html", prepare_context(context)) def collective(request, context, page_id): """коллектив""" matching_objects = Collective.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None obj = matching_objects[0] context = prepare_context_for_std_object(context, obj) context["infodata"] = [ ("Город", prepare_connected_object(obj.city)), ("Год основания", obj.year), ("Тип", format_mtm_field(obj.types)), ] context["infodata_connected"] = [ ("Записи", obj.records.filter(published=True)), ("Публикации", obj.publication_set.filter(published=True)), ("Книги", obj.book_set.filter(published=True)), ("Главы из книг", obj.bookchapter_set.filter(published=True)), ("Словарные статьи", obj.terms.filter(published=True)) ] context["model_slug"] = "collective" context["objects_name"] = "Коллективы" return render(request, "content_article.html", prepare_context(context)) def term(request, context, page_id): """словарные статьи""" matching_objects = Term.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None obj = matching_objects[0] context = prepare_context_for_std_object(context, obj) context["infodata"] = [ ("Категории словаря", format_mtm_field(obj.types)), ] context["infodata_connected"] = [ ("Книги", obj.book_set.filter(published=True)), ("Главы из книг", obj.bookchapter_set.filter(published=True)), ("Публикации", obj.publication_set.filter(published=True)), ("Персоналии", obj.person_set.filter(published=True)), ("Коллективы", obj.collective_set.filter(published=True)), ("Театры и фестивали", obj.place_set.filter(published=True)), ("Произведения", obj.composition_set.filter(published=True)), ] context["model_slug"] = "dic" context["objects_name"] = "Энциклопедия" return render(request, "content_article.html", prepare_context(context)) def book(request, context, page_id): matching_objects = Book.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None obj = matching_objects[0] context = prepare_context_for_std_object(context, obj) context["infodata"] = [ ("Автор", obj.book_author), ("Тип", format_mtm_field(obj.type)), ("Категория", format_mtm_field(obj.category)), ("Персоналии", format_mtm_field(obj.persons, lower=False)), ("Произведения", format_mtm_field(obj.compositions, lower=False)), ("Словарные статьи", format_mtm_field(obj.terms)), ("Коллективы", format_mtm_field(obj.collectives, lower=False)), ("Площадки", format_mtm_field(obj.places, lower=False)), ("Информация об издании", obj.info) ] context["chapters"] = obj.get_chapters() return render(request, "content_article.html", prepare_context(context)) def book_chapter(request, context, page_id): matching_objects = BookChapter.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None obj = matching_objects[0] context = prepare_context_for_std_object(context, obj) context["infodata"] = [ ("Персоналии", format_mtm_field(obj.persons, lower=False)), ("Произведения", format_mtm_field(obj.compositions, lower=False)), ("Словарные статьи", format_mtm_field(obj.terms)), ("Коллективы", format_mtm_field(obj.collectives, lower=False)), ("Площадки", format_mtm_field(obj.places, lower=False)), ] context["book"] = obj.book context["chapter_number"] = obj.number context["next_chapter"] = obj.get_next_chapter() context["prev_chapter"] = obj.get_prev_chapter() return render(request, "content_article.html", prepare_context(context)) def musicpage(request, context, page_id): matching_objects = MusicPage.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None obj = matching_objects[0] context = prepare_context_for_std_object(context, obj) context["infodata"] = [ ("Композитор", prepare_connected_object(obj.composer)), ("Исполнители", format_mtm_field(obj.musicians, lower=False)), ("Произведения", format_mtm_field(obj.compositions, lower=False)), ("Коллективы", format_mtm_field(obj.collectives, lower=False)), ] return render(request, "content_article.html", prepare_context(context)) def simplepage(request, context, page_id): matching_objects = Page.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None obj = matching_objects[0] context = prepare_context_for_std_object(context, obj) context["show_comments"] = False return render(request, "content_article.html", prepare_context(context)) def author(request, context, page_id): matching_objects = Author.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None obj = matching_objects[0] context = prepare_context_for_std_object(context, obj) context["infodata_connected"] = [ ("Публикации", obj.publication_set.filter(published=True)), ("Словарные статьи", obj.term_set.filter(published=True)), ("Статьи о персоналиях", obj.person_set.filter(published=True)), ("Статьи о театрах и фестивалях", obj.place_set.filter(published=True)), ("Статьи о произведениях", obj.composition_set.filter(published=True)), ("Статьи о коллективах", obj.collective_set.filter(published=True)), ("Прочие страницы сайта", obj.page_set.filter(published=True)), ] if os.environ['DJANGO_SPLIT_SETTINGS_MODULE'] == 'ON': return render(request, "author.html", prepare_context(context)) else: return render(request, "content_article.html", prepare_context(context)) def profession(request, context, page_id): matching_objects = Profession.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None return catalogs.persons(request, context, page_id) def collective_type(request, context, page_id): matching_objects = CollectiveType.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None return catalogs.collective(request, context, page_id) def place_type(request, context, page_id): matching_objects = PlaceType.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None return catalogs.place(request, context, page_id) def composition_genre(request, context, page_id): matching_objects = CompositionGenre.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None return catalogs.compositions(request, context, page_id) def term_type(request, context, page_id): matching_objects = TermType.objects.filter(slug=page_id, site__id=settings.SITE_ID) if not len(matching_objects): return None return catalogs.terms(request, context, page_id) VIEW_PREPROCESSORS = [ person, publication, composition, place, collective, term, book, simplepage, musicpage, author, book_chapter, profession, collective_type, place_type, composition_genre, term_type] # counter # вместо metric(idpage) def counter(request): import redis idpage = request.GET.get('slug') content = {} # Количество загрузок страницы if os.environ['DJANGO_SPLIT_SETTINGS_MODULE'] in ['ON', 'BEL']: if len(idpage)>0: r = redis.StrictRedis(host=settings.REDIS_HOST, port=6379, db=0) _old = 'm:{0}:y:2014'.format(idpage) stat_key = os.environ['DJANGO_SPLIT_SETTINGS_MODULE'] if stat_key == "ON": stat_key = "ON2" # Operanews was ON2 before if r.get(_old): r.zadd(stat_key, int(r.get(_old)), idpage) r.delete(_old) content['value'] = r.zincrby(stat_key, 1, idpage) return JsonResponse(content) def page(request, page_id): page_id = page_id.replace("/", "__") #context = RequestContext(request, processors=[category_to_context, bc_header_banner]) context = category_to_context(request) #context = {} context["URI"] = urllib.parse.quote(request.get_full_path()) # @todo: написать нормальную вставку банеров context['bc_header_banner'] = Ad.get_all().filter(slug='bc_header_banner') context['bc_main_header_banner'] = Ad.get_all().filter(slug='bc_main_header_banner') if os.environ['DJANGO_SPLIT_SETTINGS_MODULE'] in ['ON', 'BEL']: # начислить каунтер загрузок страницы import redis r = redis.StrictRedis(host=settings.REDIS_HOST, port=6379, db=0) _old = 'm:{0}:y:2014'.format(page_id) if r.get(_old): r.zadd(os.environ['DJANGO_SPLIT_SETTINGS_MODULE'], int(r.get(_old)), page_id) r.delete(_old) r.zincrby(os.environ['DJANGO_SPLIT_SETTINGS_MODULE'], 1, page_id) #change order in new ver - zincrby(self, name, amount, value) for preprocessor in VIEW_PREPROCESSORS: page = preprocessor(request, context, page_id) if page: return page raise Http404 def test500(request): raise Http500