[Answered ]-How to create a class just after starting Django server and access its members later in views.py

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

Leave a comment