2

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)```
helijia21
  • 23
  • 4

2 Answers2

1

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.

Matt
  • 2,153
  • 1
  • 18
  • 29
-1

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')
ycx
  • 3,155
  • 3
  • 14
  • 26
  • sorry, it doesnt work. here is the result ```starting services: test 'A' object has no attribute 'a' this class has been init this is a nameko method 'A' object has no attribute 'a' this class has been init this is a nameko method``` – helijia21 Oct 29 '19 at 06:16
  • it seems that if i use the @time property ,nameko will always initial the class A – helijia21 Oct 29 '19 at 06:20
  • what do you mean by it doesnt work? Are you unable to call A.a after creating an A object? – ycx Oct 29 '19 at 07:41
  • in this case nameko will always run the __init__ and recreate the A.a – helijia21 Oct 29 '19 at 08:03
  • In the second code snippet I gave, it will run the init and will not recreate the A.a – ycx Oct 29 '19 at 08:32