PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

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

 July 08, 2022     class, django, instance, python     No comments   

Issue

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?


Solution

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


Answered By - oruchkin
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing