Home > database >  How to create a class just after starting Django server and access its members later in views.py
How to create a class just after starting Django server and access its members later in views.py

Time:06-14

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?

CodePudding user response:

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.")
  • Related