Ejemplo n.º 1
0
def start_task_callback(n_clicks, task_id, l1, l2, data):
    """This callback is triggered by  clicking the submit button click event.  If the
    button was really pressed (as opposed to being self-triggered when the app is
    launch) it checks if the user input is valid then puts the query on the Celery
    queue.  Finally it returns the celery task ID to the invisible div called 'task-id'.
    """
    print("inside", n_clicks)
    # Don't touch this:
    slogger(
        "start_task_callback",
        f"n_clicks={n_clicks}, task_id={task_id}, l1={l1}, l2={l2}",
    )
    if n_clicks is None or n_clicks == 0:
        return "none"

    # Validate the user input.  If invalid return 'none' to task-id and don't queue
    # anything.
    if l1 is None:
        # invalid input
        slogger("start_task_callback", "user has not selected any year")
        return "none"

    # valid, so proceed
    slogger("start_task_callback", f"l1={l1} l2={l2}")

    # Put search function in the queue and return task id
    # (arguments must always be passed as a list)
    slogger("start_task_callback", "query accepted and applying to Celery")
    task = query.apply_async([l1, l2, data])
    # don't touch this:
    slogger("start_Task_callback", f"query is on Celery, task-id={task.id}")
    return str(task.id)
Ejemplo n.º 2
0
def simulation(*args):
    """Evaluate the spectrum and update the plot."""

    if not ctx.triggered:
        slogger("simulation", "simulation stopped, ctx not triggered")
        raise PreventUpdate

    return one_time_simulation()
Ejemplo n.º 3
0
def show_hide_spinner(n_intervals, task_status):
    """This callback is triggered by then Interval clock and checks the task progress
    via the invisible div 'task-status'.  If a task is running it will show the spinner,
    otherwise it will be hidden."""
    if task_status == "PROGRESS":
        slogger("show_hide_spinner", "show spinner")
        return None

    slogger(
        "show_hide_spinner",
        "hide spinner because task_status={}".format(task_status),
    )
    return {"display": "none"}
Ejemplo n.º 4
0
def get_results(task_status, task_id):
    """This callback is triggered by task-status. It checks the task status, and if the
    status is 'SUCCESS' it retrieves results, defines the results form and returns it,
    otherwise it returns [] so that nothing is displayed"""
    if task_status == "SUCCESS":
        # Fetch results from Celery and forget the task
        slogger("get_results",
                "retrieve results for task-id {} from Celery".format(task_id))
        result = AsyncResult(task_id).result  # fetch results
        AsyncResult(task_id).forget()  # delete from Celery
        # Display a message if their were no hits
        if result == [{}]:
            return [
                "We couldn't find any results.  Try broadening your search."
            ]
        # Otherwise return the populated DataTable
        return result

    raise PreventUpdate
Ejemplo n.º 5
0
def update_input_graph(contents, tr_val, url, figure, data):
    # if contents is None:
    #     raise PreventUpdate

    trigger_id = ctx.triggered[0]["prop_id"].split(".")[0]
    if trigger_id == "url-search":
        slogger("url", url)
        if url in [None, ""]:
            raise PreventUpdate

        response = urlopen(url[3:])
        content = json.loads(response.read())
        exp_data = cp.parse_dict(content)
        pre_figure(exp_data, figure)
        return [figure, exp_data.real.dict()]

    if trigger_id == "INV-upload-from-graph":
        content = contents.split(",")[1]

        decoded = base64.b64decode(content)
        success, exp_data, _ = load_csdm(decoded)

        if not success:
            raise PreventUpdate

        pre_figure(exp_data, figure)
        return [figure, exp_data.real.dict()]

    if trigger_id == "INV-transpose":
        if data is None:
            raise PreventUpdate
        data = cp.parse_dict(data).T

        figure["data"][0]["x"] = data.x[0].coordinates.value
        figure["data"][0]["y"] = data.x[1].coordinates.value
        figure["data"][0]["z"] = data.y[0].components[0]
        return [figure, data.dict()]
Ejemplo n.º 6
0
def toggle_interval_speed(task_id, task_status):
    """This callback is triggered by changes in task-id and task-status divs. It
    switches the page refresh interval to fast (1 sec) if a task is running, or slow
    (24 hours) if a task is pending or complete."""
    if task_id == "none":
        slogger("toggle_interval_speed", "no task-id --> slow refresh")
        return 24 * 60 * 60 * 1000

    if task_id != "none" and (task_status in ["SUCCESS", "FAILURE"]):
        slogger(
            "toggle_interval_speed",
            f"task-id is {task_id} and status is {task_status} --> slow refresh",
        )
        return 24 * 60 * 60 * 1000

    slogger(
        "toggle_interval_speed",
        f"task-id is {task_id} and status is {task_status} --> fast refresh",
    )
    return 5000
Ejemplo n.º 7
0
def query(self, l1, l2, data):
    task_id = self.request.id
    slogger("query", "query in progress, task_id={}".format(task_id))
    # Don't touch this:
    self.update_state(state="PROGRESS")
    time.sleep(
        1.5
    )  # a short dwell is necessary for other async processes to catch-up
    # Change all of this to whatever you want:
    results = solve(l1, l2, data)
    slogger("query", "check results and process if necessary")
    # Only write an Excel file for download if there were actual results
    # if len(results) > 0:
    #     # Save locally in Excel format then copy the file to S3 because any local
    #     # files store locally in the container are highly volatile and
    #     # will likely be deleted before the user has a chance to download
    #     reports_folder = os.path.join(
    #         os.path.dirname(os.path.realpath(__file__)), "reports"
    #     )
    #     # Use the Celery task id as the filename (we change it to something more
    #     # userfriendly later)
    #     filename = f"{task_id}.csdf"
    #     # excel_filename = "{}.xlsx".format(task_id)
    #     local_excel_path = os.path.join(reports_folder, filename)
    #     # slogger("query", f"saving full report locally as {local_excel_path}")
    #     # excel_writer = pd.ExcelWriter(local_excel_path, engine="xlsxwriter")
    #     # # Here you can customize the name of the Excel sheet:
    #     # pd.DataFrame(results).to_excel(
    #     #     excel_writer, sheet_name="BoilerplateResults", index=False
    #     # )
    #     # excel_writer.save()

    #     # Copy to S3 if enabled
    #     # if config.DISABLE_S3 == False:
    #     #     bucket_name = os.environ["S3_BUCKET_NAME"]
    #     #     # We prefix the S3 key with the name of the app - you can change this if
    #     #       you want:
    #     #     s3_excel_key = "{}/{}".format(config.DASH_APP_NAME, excel_filename)
    #     #     slogger(
    #     #         "query",
    #     #         "copying {} to S3 bucket {} with key {}".format(
    #     #             local_excel_path, bucket_name, s3_excel_key
    #     #         ),
    #     #     )
    #     #     client = boto3.client(
    #     #         "s3",
    #     #         aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"],
    #     #         aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"],
    #     #     )
    #     #     body = open(local_excel_path, "rb")
    #     #     client.put_object(Bucket=bucket_name, Key=s3_excel_key, Body=body)
    #     # else:
    #     slogger(
    #         "query",
    #         "caution - S3 is disabled so the Download Excel link will be broken!",
    #     )
    # else:
    slogger("query", "empty results - nothing was saved")

    # Return results for display
    slogger("query", "return results")
    return results