File: worker.py

package info (click to toggle)
pyro5 5.15-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 2,112 kB
  • sloc: python: 14,291; makefile: 163; sh: 66; javascript: 62
file content (39 lines) | stat: -rw-r--r-- 1,315 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import os
import socket
from math import sqrt
from Pyro5.api import expose, Daemon, locate_ns
import Pyro5.socketutil


class Worker(object):
    @expose
    def factorize(self, n):
        print("factorize request received for", n)
        result = self._factorize(n)
        print("    -->", result)
        return result

    def _factorize(self, n):
        """simple algorithm to find the prime factorials of the given number n"""

        def isPrime(n):
            return not any(x for x in range(2, int(sqrt(n)) + 1) if n % x == 0)

        primes = []
        candidates = range(2, n + 1)
        candidate = 2
        while not primes and candidate in candidates:
            if n % candidate == 0 and isPrime(candidate):
                primes = primes + [candidate] + self._factorize(n // candidate)
            candidate += 1
        return primes


with Daemon(host=Pyro5.socketutil.get_ip_address(None)) as daemon:
    # create a unique name for this worker (otherwise it overwrites other workers in the name server)
    worker_name = "Worker_%d@%s" % (os.getpid(), socket.gethostname())
    print("Starting up worker", worker_name)
    uri = daemon.register(Worker)
    with locate_ns() as ns:
        ns.register(worker_name, uri, metadata={"example3.worker.factorizer"})
    daemon.requestLoop()