Maxximiliann

Maxximiliann

defmodule Supervisor.PyOperatorManager do
  use Supervisor

  def start_link(_) do
    Supervisor.start_link(__MODULE__, [], name: __MODULE__)
  end

  @impl true
  def init(_) do
    Process.flag(:trap_exit, true)

    children = [
      :poolboy.child_spec(:py_pool,
        name: {:local, :py_pool},
        worker_module: Server.PyOperator,
        size: 10,
        max_overflow: 5
      )
    ]

    Supervisor.init(children, strategy: :one_for_one)
  end

  def launch(data \\ [], py_module, py_lambda) do
    :poolboy.transaction(:py_pool, fn pid ->
      GenServer.call(pid, {data, py_module, py_lambda}, 30_000)
    end)
  end
end
defmodule Server.PyOperator do
  use GenServer
  use Export.Python

  def start_link(_) do
    GenServer.start_link(__MODULE__, %{})
  end

  @impl true
  def init(state) do
    Process.flag(:trap_exit, true)

    priv_path = Path.join(:code.priv_dir(:arbit), "python")
    {:ok, py} = Python.start_link(python_path: priv_path)
    {:ok, Map.put(state, :py, py)}
  end

  @impl true
  def handle_call({data, py_module, py_lambda}, _from, %{py: py} = state) do
    results = Python.call(py, py_module, py_lambda, [data])

    results
    |> IO.inspect(label: "#{__MODULE__} - line 23")

    {:reply, results, state}
  end

  @impl true
  def terminate(_reason, %{py: py}) do
    Python.stop(py)
    :ok
  end
end
#foo.py
import simplejson as json
from erlport.erlterms import Atom
from heavy_processes import some_heavy_process
from some_lib.errors import (AuthenticationError, PermissionDenied, ArgumentsRequired, BadRequest, 
                        BadResponse, NullResponse, NotSupported, NetworkError, DDoSProtection,
                        RateLimitExceeded, OnMaintenance, InvalidNonce, RequestTimeout)


def transmit_report(success_status, report, id, category, misc):
    success_status_as_bytes = bytes(success_status, encoding='utf8')
    full_report = report | {
        'id': id, 'category': category, 'misc?': misc}
    full_report_json = json.dumps(full_report)

    return (Atom(success_status_as_bytes), (full_report_json))


def do_stuff(params_json):
    params = json.loads(params_json)

    id = params["id"]
    category = params["category"]
    misc = params["misc"]

    arg1 = params["arg1"]
    arg2 = params["arg2"]
    arg3 = params["arg3"]
    arg4 = params["arg4"]
    arg5 = params["arg5"]

    try:
        report = some_heavy_process(
            arg1, arg2, arg3, arg4, arg5)

    except (AuthenticationError, PermissionDenied, ArgumentsRequired, BadRequest, BadResponse,
            NullResponse, NotSupported, NetworkError, DDoSProtection,
            RateLimitExceeded, OnMaintenance, InvalidNonce, RequestTimeout) as error:

        transmit_report(
            'error', {'error': str(error)}, id, category, misc)
    except Exception as crash_report:
        transmit_report('error', {'error': str(
            crash_report)}, id, category, misc)
    else:
        transmit_report(
            'ok', report, id, category, misc)


def main(params_json):
    do_stuff(params_json)


if __name__ == '__main__':
    main(params_json)

Issue:
Calling Supervisor.PyOperatorManager.launch(params_json, "foo", "main") only returns :undefined instead of the tuple from transmit_report.

How is this issue resolved?

First Post! Switch mode

Maxximiliann

Maxximiliann OP

Fix:

def main(params_json):
    return do_stuff(params_json)

Modification:

  • Added explicit return keyword to main(params_json) method. In contrast to Elixir, return values in Python must be explicitly assigned to the return keyword or they will be discarded.

Note:

  • Python does not support hot code reloading. Because files are built as they are imported, restarting iex is required for code changes to take effect.
— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement