about summary refs log tree commit diff
path: root/uploader
diff options
context:
space:
mode:
Diffstat (limited to 'uploader')
-rw-r--r--uploader/background_jobs.py5
-rw-r--r--uploader/phenotypes/views.py77
-rw-r--r--uploader/route_utils.py12
-rw-r--r--uploader/templates/background-jobs/default-success-page.html17
-rw-r--r--uploader/templates/phenotypes/view-dataset.html32
5 files changed, 124 insertions, 19 deletions
diff --git a/uploader/background_jobs.py b/uploader/background_jobs.py
index dc9f837..d33c498 100644
--- a/uploader/background_jobs.py
+++ b/uploader/background_jobs.py
@@ -56,7 +56,7 @@ def register_job_handlers(job: str):
         return getattr(module, _parts[-1])
 
     metadata = job["metadata"]
-    if metadata["success_handler"]:
+    if metadata.get("success_handler"):
         _success_handler = __load_handler__(metadata["success_handler"])
         try:
             _error_handler = __load_handler__(metadata["error_handler"])
@@ -76,8 +76,7 @@ def handler(job: dict, handler_type: str) -> HandlerType:
     ).get(handler_type)
     if bool(_handler):
         return _handler(job)
-    raise Exception(# pylint: disable=[broad-exception-raised]
-        f"No '{handler_type}' handler registered for job type: {_job_type}")
+    return render_template("background-jobs/default-success-page.html", job=job)
 
 
 error_handler = partial(handler, handler_type="error")
diff --git a/uploader/phenotypes/views.py b/uploader/phenotypes/views.py
index ac36ec8..7002ccd 100644
--- a/uploader/phenotypes/views.py
+++ b/uploader/phenotypes/views.py
@@ -60,6 +60,7 @@ from .models import (dataset_by_id,
                      datasets_by_population,
                      phenotype_publication_data)
 
+logger = logging.getLogger(__name__)
 phenotypesbp = Blueprint("phenotypes", __name__)
 render_template = make_template_renderer("phenotypes")
 
@@ -233,11 +234,6 @@ def view_phenotype(# pylint: disable=[unused-argument]
                                     population["Id"],
                                     dataset["Id"],
                                     xref_id)
-        def __non_empty__(value) -> bool:
-            if isinstance(value, str):
-                return value.strip() != ""
-            return bool(value)
-
         return render_template(
             "phenotypes/view-phenotype.html",
             species=species,
@@ -1008,3 +1004,74 @@ def load_data_success(
                                        fragment="")))
         except JobNotFound as _jnf:
             return render_template("jobs/job-not-found.html", job_id=job_id)
+
+
+@phenotypesbp.route(
+    "<int:species_id>/populations/<int:population_id>/phenotypes/datasets"
+    "/<int:dataset_id>/recompute-means",
+    methods=["POST"])
+@require_login
+@with_dataset(
+    species_redirect_uri="species.populations.phenotypes.index",
+    population_redirect_uri="species.populations.phenotypes.select_population",
+    redirect_uri="species.populations.phenotypes.list_datasets")
+def recompute_means(# pylint: disable=[unused-argument]
+        species: dict,
+        population: dict,
+        dataset: dict,
+        **kwargs
+):
+    """Compute/Recompute the means for phenotypes in a particular population."""
+    _jobs_db = app.config["ASYNCHRONOUS_JOBS_SQLITE_DB"]
+    _job_id = uuid.uuid4()
+    _xref_ids = tuple(int(item.split("_")[-1])
+                      for item in request.form.getlist("selected-phenotypes"))
+
+    _loglevel = logging.getLevelName(app.logger.getEffectiveLevel()).lower()
+    command = [
+        sys.executable,
+        "-u",
+        "-m",
+        "scripts.compute_phenotype_means",
+        app.config["SQL_URI"],
+        _jobs_db,
+        str(population["Id"]),
+        "--log-level",
+        _loglevel] + (
+            ["--cross-ref-ids", ",".join(str(_id) for _id in _xref_ids)]
+            if len(_xref_ids) > 0 else
+            [])
+    logger.debug("%s.recompute_means: command (%s)", __name__, command)
+
+    with sqlite3.connection(_jobs_db) as conn:
+        _job = gnlibs_jobs.launch_job(
+            gnlibs_jobs.initialise_job(
+                conn,
+                _job_id,
+                command,
+                "(re)compute-phenotype-means",
+                extra_meta={
+                    "species_id": species["SpeciesId"],
+                    "population_id": population["Id"],
+                    "dataset_id": dataset["Id"],
+                    "success_handler": (
+                        "uploader.phenotypes.views."
+                        "recompute_phenotype_means_success_handler")
+            }),
+            _jobs_db,
+            Path(f"{app.config['UPLOAD_FOLDER']}/job_errors"),
+            worker_manager="gn_libs.jobs.launcher",
+            loglevel=_loglevel)
+        return redirect(url_for("background-jobs.job_status",
+                                job_id=_job["job_id"]))
+
+
+def recompute_phenotype_means_success_handler(job):
+    """Handle loading new phenotypes into the database successfully."""
+    flash("Means computed successfully!", "alert alert-success")
+    return redirect(url_for(
+        "species.populations.phenotypes.view_dataset",
+        species_id=job["metadata"]["species_id"],
+        population_id=job["metadata"]["population_id"],
+        dataset_id=job["metadata"]["dataset_id"],
+        job_id=job["job_id"]))
diff --git a/uploader/route_utils.py b/uploader/route_utils.py
index 63b2852..53247e6 100644
--- a/uploader/route_utils.py
+++ b/uploader/route_utils.py
@@ -1,5 +1,5 @@
 """Generic routing utilities."""
-import json
+import logging
 from json.decoder import JSONDecodeError
 
 from flask import (flash,
@@ -15,6 +15,8 @@ from uploader.datautils import base64_encode_dict, base64_decode_to_dict
 from uploader.population.models import (populations_by_species,
                                         population_by_species_and_id)
 
+logger = logging.getLogger(__name__)
+
 def generic_select_population(
         # pylint: disable=[too-many-arguments, too-many-positional-arguments]
         species: dict,
@@ -56,9 +58,9 @@ def redirect_to_next(default: dict):
     assert "uri" in default, "You must provide at least the 'uri' value."
     try:
         next_page = base64_decode_to_dict(request.args.get("next"))
-        return redirect(url_for(
-            next_page["uri"],
-            **{key:value for key,value in next_page.items()}))
+        _uri = next_page["uri"]
+        next_page.pop("uri")
+        return redirect(url_for(_uri, **next_page))
     except (TypeError, JSONDecodeError) as _err:
         logger.debug("We could not decode the next value '%s'",
                      next_page,
@@ -66,7 +68,7 @@ def redirect_to_next(default: dict):
 
     return redirect(url_for(
         default["uri"],
-        **{key:value for key,value in default.items()}))
+        **{key:value for key,value in default.items() if key != "uri"}))
 
 
 def build_next_argument(uri: str, **kwargs) -> str:
diff --git a/uploader/templates/background-jobs/default-success-page.html b/uploader/templates/background-jobs/default-success-page.html
new file mode 100644
index 0000000..5732456
--- /dev/null
+++ b/uploader/templates/background-jobs/default-success-page.html
@@ -0,0 +1,17 @@
+{%extends "phenotypes/base.html"%}
+{%from "flash_messages.html" import flash_all_messages%}
+
+{%block title%}Background Jobs: Success{%endblock%}
+
+{%block pagetitle%}Background Jobs: Success{%endblock%}
+
+{%block contents%}
+{{flash_all_messages()}}
+
+<div class="row">
+  <p>Job <strong>{{job.job_id}}</strong>,
+    {%if job.get("metadata", {}).get("job-type")%}
+    of type '<em>{{job.metadata["job-type"]}}</em>
+    {%endif%}' completed successfully.</p>
+</div>
+{%endblock%}
diff --git a/uploader/templates/phenotypes/view-dataset.html b/uploader/templates/phenotypes/view-dataset.html
index 306dcce..6a261fc 100644
--- a/uploader/templates/phenotypes/view-dataset.html
+++ b/uploader/templates/phenotypes/view-dataset.html
@@ -46,12 +46,32 @@
 </div>
 
 <div class="row">
-  <p><a href="{{url_for('species.populations.phenotypes.add_phenotypes',
-              species_id=species.SpeciesId,
-              population_id=population.Id,
-              dataset_id=dataset.Id)}}"
-        title="Add a bunch of phenotypes"
-        class="btn btn-primary">Add phenotypes</a></p>
+  <div class="col">
+    <a href="{{url_for('species.populations.phenotypes.add_phenotypes',
+             species_id=species.SpeciesId,
+             population_id=population.Id,
+             dataset_id=dataset.Id)}}"
+       title="Add a bunch of phenotypes"
+       class="btn btn-primary">Add phenotypes</a>
+  </div>
+
+  <div class="col">
+    <form id="frm-recompute-phenotype-means"
+          method="POST"
+          action="{{url_for(
+                  'species.populations.phenotypes.recompute_means',
+                  species_id=species['SpeciesId'],
+                  population_id=population['Id'],
+                  dataset_id=dataset['Id'])}}"
+          class="d-flex flex-row align-items-center flex-wrap"
+          style="display: inline;">
+      <input type="submit"
+             title="Compute/Recompute the means for all phenotypes."
+             class="btn btn-info"
+             value="(rec/c)ompute means"
+             id="submit-frm-recompute-phenotype-means" />
+    </form>
+  </div>
 </div>
 
 <div class="row">