def authority(request, authority_id):
    """
    View for individual Authority entries.
    """

    authority = Authority.objects.get(id=authority_id)

    if not authority.public:
        return HttpResponseForbidden()

    # Some authority entries are deleted. These should be hidden from public
    #  view.
    if authority.record_status == 'DL':
        return Http404("No such Authority")

    # If the user has been redirected from another Authority entry, this should
    #  be indicated in the view.
    redirect_from_id = request.GET.get('redirect_from')
    if redirect_from_id:
        redirect_from = Authority.objects.get(pk=redirect_from_id)
    else:
        redirect_from = None

    # There are several authority entries that redirect to other entries,
    #  usually because the former is a duplicate of the latter.
    if authority.record_status == 'RD' and authority.redirect_to is not None:
        redirect_kwargs = {'authority_id': authority.redirect_to.id}
        base_url = reverse('authority', kwargs=redirect_kwargs)
        redirect_url = base_url + '?redirect_from={0}'.format(authority.id)
        return HttpResponseRedirect(redirect_url)

    template = loader.get_template('isisdata/authority.html')

    show_nr = 3
    related_citations_author = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['AU'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_author_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['AU']).distinct('citation_id').count()

    related_citations_editor = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['ED'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_editor_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['ED'], citation__public=True).distinct('citation_id').count()

    related_citations_advisor = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['AD'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_advisor_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['AD'], citation__public=True).distinct('citation_id').count()

    related_citations_contributor = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['CO'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_contributor_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['CO'], citation__public=True).distinct('citation_id').count()

    related_citations_translator = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['TR'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_translator_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['TR'], citation__public=True).distinct('citation_id').count()

    related_citations_subject = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['SU'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_subject_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['SU'], citation__public=True).distinct('citation_id').count()

    related_citations_category = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['CA'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_category_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['CA'], citation__public=True).distinct('citation_id').count()

    related_citations_publisher = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['PU'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_publisher_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['PU'], citation__public=True).distinct('citation_id').count()

    related_citations_school = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['SC'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_school_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['SC'], citation__public=True).distinct('citation_id').count()

    related_citations_institution = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['IN'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_institution_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['IN'], citation__public=True).distinct('citation_id').count()

    related_citations_meeting = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['ME'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_meeting_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['ME'], citation__public=True).distinct('citation_id').count()

    related_citations_periodical = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['PE'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_periodical_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['PE'], citation__public=True).distinct('citation_id').count()

    related_citations_book_series = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['BS'], citation__public=True).order_by('-citation__publication_date')[:show_nr]
    related_citations_book_series_count = ACRelation.objects.filter(authority=authority,
                                                  type_controlled__in=['BS'], citation__public=True).distinct('citation_id').count()

    # Location of authority in REST API
    api_view = reverse('authority-detail', args=[authority.id], request=request)

    # Provide progression through search results, if present.
    last_query = request.GET.get('last_query', None) #request.session.get('last_query', None)
    query_string = request.GET.get('query_string', None)
    fromsearch = request.GET.get('fromsearch', False)
    if query_string:
        query_string = query_string.encode('ascii','ignore')
        search_key = base64.b64encode(query_string) #request.session.get('search_key', None)
    else:
        search_key = None

    # This is the database cache.
    user_cache = caches['default']
    search_results = user_cache.get('search_results_authority_' + str(search_key))

    # make sure we have a session key
    if hasattr(request, 'session') and not request.session.session_key:
        request.session.save()
        request.session.modified = True

    session_id = request.session.session_key
    page_authority = user_cache.get(session_id + '_page_authority', None)

    if search_results and fromsearch and page_authority:
        search_count = search_results.count()
        prev_search_result = None
        if (page_authority > 1):
            prev_search_result = search_results[(page_authority - 1)*20 - 1]

        # if we got to the last result of the previous page we need to count down the page number
        if prev_search_result == 'isisdata.authority.' + authority_id:
            page_authority = page_authority - 1
            user_cache.set(session_id + '_page_authority', page_authority)

        search_results_page = search_results[(page_authority - 1)*20:page_authority*20 + 2]

        try:
            search_index = search_results_page.index('isisdata.authority.' + authority_id) + 1   # +1 for display.
            if search_index == 21:
                user_cache.set(session_id + '_page_authority', page_authority+1)

        except (IndexError, ValueError):
            search_index = None
        try:
            search_next = search_results_page[search_index]
        except (IndexError, ValueError, TypeError):
            search_next = None
        try:
            search_previous = search_results_page[search_index - 2]
            if search_index - 2 == -1:
                search_previous = prev_search_result

        # !! Why are we catching all of these errors?
        except (__HOLE__, ValueError, AssertionError, TypeError):
            search_previous = None
        if search_index:
            search_current = search_index + (20* (page_authority - 1))
        else:
            search_current = None
    else:
        search_index = None
        search_next = None
        search_previous = None
        search_current = None
        search_count = None


    context = RequestContext(request, {
        'authority_id': authority_id,
        'authority': authority,
        'related_citations_author': related_citations_author,
        'related_citations_author_count': related_citations_author_count,
        'related_citations_editor': related_citations_editor,
        'related_citations_editor_count': related_citations_editor_count,
        'related_citations_advisor': related_citations_advisor,
        'related_citations_advisor_count': related_citations_advisor_count,
        'related_citations_contributor': related_citations_contributor,
        'related_citations_contributor_count': related_citations_contributor_count,
        'related_citations_translator': related_citations_translator,
        'related_citations_translator_count': related_citations_translator_count,
        'related_citations_subject': related_citations_subject,
        'related_citations_subject_count': related_citations_subject_count,
        'related_citations_category': related_citations_category,
        'related_citations_category_count': related_citations_category_count,
        'related_citations_publisher': related_citations_publisher,
        'related_citations_publisher_count': related_citations_publisher_count,
        'related_citations_school': related_citations_school,
        'related_citations_school_count': related_citations_school_count,
        'related_citations_institution': related_citations_institution,
        'related_citations_institution_count': related_citations_institution_count,
        'related_citations_meeting': related_citations_meeting,
        'related_citations_meeting_count': related_citations_meeting_count,
        'related_citations_periodical': related_citations_periodical,
        'related_citations_periodical_count': related_citations_periodical_count,
        'related_citations_book_series': related_citations_book_series,
        'related_citations_book_series_count': related_citations_book_series_count,
        'source_instance_id': authority_id,
        'source_content_type': ContentType.objects.get(model='authority').id,
        'api_view': api_view,
        'redirect_from': redirect_from,
        'search_results': search_results,
        'search_index': search_index,
        'search_next': search_next,
        'search_previous': search_previous,
        'search_current': search_current,
        'search_count': search_count,
        'fromsearch': fromsearch,
        'last_query': last_query,
        'query_string': query_string,
    })
    return HttpResponse(template.render(context))
dataset/ETHPy150Open upconsulting/IsisCB/isiscb/isisdata/views.py/authority