how to stop initial class when use nameko run a service

341 Views Asked by At

Hi here is an example of my project, I would like to use nameko run Test:A, And I find that the class A will be inital repeatedly during run this service. Actuallly,I want to connect to a service and do something repeat and I don't want to initial the connection every time. So is there any good method to solve this?

###FileName:Test.py###
from nameko.timer import timer
import time
class A:
    name = 'test'
    def __init__(self):
        self.a = 'a'
        print('this class has been init')

    @timer(interval=0)
    def test(self):
        try:
            print('this is a nameko method')
        except:
            pass
        time.sleep(1)

    @timer(interval=2)
    def test2(self):
        try:
            print('second nameko method')
        except:
            pass
        time.sleep(3)```
2

There are 2 best solutions below

0
On BEST ANSWER

Nameko services are implemented as classes, but they don't behave like normal classes in terms of object-oriented programming.

In particular, the class is instantiated for every worker, i.e. every time an entrypoint fires. That's why you see "this class has been init" over and over.

In general, you shouldn't use a constructor in a Nameko service class.

To manage connections and one-time setup for a service you should use a DependencyProvider.

5
On

You could try:

class A:
    name = 'test'
    def __init__(self):
        try:
            self.a
        except Exception as e:
            print (e)
            self.a = 'a'
        print('this class has been init')

This will check that self.a is already in scope, and if yes, it will not assign it to 'a'. Else, it will do so.

If this is not what you want, you could also make a a class variable instead of an instance variable.

class A:
    name = 'test'
    def __init__(self):
        try:
            A.a
            print (A.a) #nothing
        except Exception as e:
            print (e)
            A.a = 'a'
            print (A.a) #created
        print('this class has been init')