1

I encountered a simple issue in Django, there were similar questions on this forum but haven't answered correctly so i'm writing it again.
My issue is just same as this question. How to instantiate a class just after starting Django server and access its members later in views.py

I have to instantiate custom class when server is starts, and should integrate in the view by accessing methods of instantiated custom class.
Let's say we made this class and instantiated when server starts and stored to variables that can be used in later like in urls.py or somewhere. (I don't know how)

class MyClass:
  def __init__(self):
    self.a=3
  def foo(self):
    return self.a
...

#When django server starts
new=MyClass()

In the view.py, let's say that there is some magic that passes instantiated instance as a parameter in view's method.

def index(request, instantiatedClass :MyClass):
  a=instantiatedClass.foo()
  return HttpResponse(f"{a} is your var.")

This is what I want. but I investigated and in the urls.py there is no options that can passes custom parameters to pointed views.py's method other than passing url information by the user.

I believe that Django's model behave and instantiated not same way like ordinary class.

So how can I achieve this?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Oh Wan Sik
  • 75
  • 1
  • 9
  • Why do you want this? Is not it enough to create a class and use it when it needed – enes islam Jun 14 '22 at 10:38
  • @enesislam I'm managing movie recommendation website project, Already created UserDB class and MovieDB class that contains user and movie databases in certain format, and There is Recommender class that trains by integrating UserDB and MovieDB to recommend movies to user. we made this all previously and now i have to serve it to user using django framework. – Oh Wan Sik Jun 14 '22 at 10:59

1 Answers1

1

Everything you declared outside the functions in views.py will be initiated after you start your server only once. In this case your new variable will be an instance of MyClass and it will be stored in the RAM, once you restart your server, it's data will be lost.

any_views.py

class MyClass:
  def __init__(self):
    self.a = 3
  def foo(self):
    return self.a

new = MyClass()

def index(request):
  a = new.foo()
  print(a)
  return HttpResponse(f"{a} is your var.")
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
oruchkin
  • 1,145
  • 1
  • 10
  • 21