Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

everything you declare outsided 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.")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading