views.py 7.11 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
13
import os
14 15
import requests

carlosribas's avatar
carlosribas committed
16
from datetime import date, timedelta
17
from django.conf import settings
18
from django.shortcuts import render
19
from django.views.decorators.cache import never_cache
20
from rest_framework.response import Response
21 22
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
23

24 25 26 27

if settings.ENVIRONMENT == 'HX':
    SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002'
else:
28
    SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
29

30 31 32 33 34 35 36 37 38 39 40 41 42 43
if settings.ENVIRONMENT == 'DEV':
    proxies = None
elif settings.ENVIRONMENT == 'HX' or settings.ENVIRONMENT == 'OY':
    proxies = {
        'http': 'http://hx-wwwcache.ebi.ac.uk:3128',
        'https': 'http://hx-wwwcache.ebi.ac.uk:3128'
    }
elif settings.ENVIRONMENT == 'PG':
    proxies = {
        'http': 'http://pg-wwwcache.ebi.ac.uk:3128',
        'https': 'http://pg-wwwcache.ebi.ac.uk:3128'
    }


44 45
def proxy_request(request, url, method):
    if method == 'POST':
46
        params = request.POST
47
        if proxies:
48
            response = requests.post(url, params=params, json=request.data, proxies=proxies)
49
        else:
50
            response = requests.post(url, params=params, json=request.data)
51
    elif method == 'GET':
52
        params = request.GET
53
        if proxies:
54
            response = requests.get(url, params=params, proxies=proxies)
55
        else:
56
            response = requests.get(url, params=params)
57 58 59 60 61 62 63 64 65
    else:
        raise ValueError("Unknown method: %s" % method)

    if response.status_code < 400:
        return Response(response.json(), status=response.status_code)
    else:
        return Response(response.content, status=response.status_code)


66 67 68 69
@never_cache
@api_view(['POST'])
@permission_classes([AllowAny])
def submit_job(request):
70
    """Submit a job to sequence search service."""
71
    url = SEQUENCE_SEARCH_ENDPOINT + '/api/submit-job'
72
    return proxy_request(request, url, 'POST')
73 74


75 76 77 78
@never_cache
@api_view(['GET'])
@permission_classes([AllowAny])
def job_status(request, job_id):
79
    """Displays status of a job."""
80
    url = SEQUENCE_SEARCH_ENDPOINT + '/api/job-status/' + job_id
81
    return proxy_request(request, url, 'GET')
82 83


84 85 86 87
@never_cache
@api_view(['GET'])
@permission_classes([AllowAny])
def job_results(request, job_id):
88
    """Displays results of a finished job."""
89
    url = SEQUENCE_SEARCH_ENDPOINT + '/api/facets-search/' + job_id
90
    return proxy_request(request, url, 'GET')
91

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
@never_cache
@api_view(['GET'])
@permission_classes([AllowAny])
def infernal_job_status(request, job_id):
    """Displays status of infernal job."""
    url = SEQUENCE_SEARCH_ENDPOINT + '/api/infernal-status/' + job_id
    return proxy_request(request, url, 'GET')


@never_cache
@api_view(['GET'])
@permission_classes([AllowAny])
def infernal_job_results(request, job_id):
    """Displays results of a finished infernal job."""
    url = SEQUENCE_SEARCH_ENDPOINT + '/api/infernal-result/' + job_id
    return proxy_request(request, url, 'GET')

109 110 111 112 113 114 115 116 117 118

@never_cache
@api_view(['GET'])
@permission_classes([AllowAny])
def show_searches(request):
    """Displays info about searches."""
    url = SEQUENCE_SEARCH_ENDPOINT + '/api/show-searches'
    return proxy_request(request, url, 'GET')


119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
def sequence_search(request):
    """Sequence search main page"""
    path = os.path.join(
        settings.PROJECT_PATH,
        'rnacentral',
        'sequence_search',
        'static',
        'rnacentral-sequence-search-embed',
        'dist',
        'RNAcentral-sequence-search.js'
    )
    # Check if the embeddable component is installed
    plugin_installed = True if os.path.isfile(path) else False

    context = {'plugin_installed': plugin_installed}
    return render(request, 'sequence-search-embed.html', {'context': context})


137 138 139 140
def dashboard(request):
    """Info about searches in rnacentral-sequence-search."""
    all_searches, searches_last_24_hours, searches_last_week = 0, 0, 0
    average_all_searches, average_last_24_hours, average_last_week = 0, 0, 0
141
    searches_per_month = None
Carlos Eduardo Ribas's avatar
Carlos Eduardo Ribas committed
142
    expert_db_results = None
143 144 145 146 147 148 149
    show_searches_url = SEQUENCE_SEARCH_ENDPOINT + '/api/show-searches'

    try:
        response_url = requests.get(show_searches_url)
        if response_url.status_code == 200:
            data = response_url.json()

Carlos Eduardo Ribas's avatar
Carlos Eduardo Ribas committed
150 151 152 153 154 155 156 157
            all_searches = data['all_searches_result']['count']
            average_all_searches = data['all_searches_result']['avg_time']
            searches_last_24_hours = data['last_24_hours_result']['count']
            average_last_24_hours = data['last_24_hours_result']['avg_time']
            searches_last_week = data['last_week_result']['count']
            average_last_week = data['last_week_result']['avg_time']
            searches_per_month = data['searches_per_month']
            expert_db_results = data['expert_db_results']
158 159 160 161

    except requests.exceptions.HTTPError as err:
        raise err

carlosribas's avatar
carlosribas committed
162 163 164 165 166 167 168 169
    current_date = date.today()
    current_month = current_date.strftime('%Y-%m')
    last_month = (current_date.replace(day=1) - timedelta(days=1)).strftime('%Y-%m')
    current_month_pie_chart = []
    last_month_pie_chart = []

    for index in range(len(expert_db_results)):
        for key in expert_db_results[index]:
170 171 172 173 174 175 176
            get_current_month = list(expert_db_results[index][key][-1]) if list(expert_db_results[index][key]) else None
            get_current_month = get_current_month.pop() if get_current_month else None

            get_last_month = list(expert_db_results[index][key][-2]) if list(expert_db_results[index][key]) else None
            get_last_month = get_last_month.pop() if get_last_month else None

            if get_current_month == current_month:
carlosribas's avatar
carlosribas committed
177
                current_month_pie_chart.append({key: expert_db_results[index][key][-1][current_month]})
178
            if get_current_month == last_month:
carlosribas's avatar
carlosribas committed
179
                last_month_pie_chart.append({key: expert_db_results[index][key][-1][last_month]})
180
            if get_last_month == last_month:
carlosribas's avatar
carlosribas committed
181 182
                last_month_pie_chart.append({key: expert_db_results[index][key][-2][last_month]})

183 184 185 186 187 188
    context = {
        'all_searches': all_searches,
        'searches_last_24_hours': searches_last_24_hours,
        'searches_last_week': searches_last_week,
        'average_all_searches': average_all_searches,
        'average_last_24_hours': average_last_24_hours,
189
        'average_last_week': average_last_week,
Carlos Eduardo Ribas's avatar
Carlos Eduardo Ribas committed
190
        'searches_per_month': searches_per_month,
carlosribas's avatar
carlosribas committed
191 192 193
        'expert_db_results': expert_db_results,
        'current_month_pie_chart': current_month_pie_chart,
        'last_month_pie_chart': last_month_pie_chart
194 195 196
    }

    return render(request, 'dashboard.html', {'context': context})