How to inject an attribute or an object into a view in Django Rest Framework?









up vote
0
down vote

favorite












I am kinda new to Django Rest Framework.



I have a views.py that looks something like this:



class MyAPIView(APIView):
""" My API """

def get(self, request, path):
""" Handles GET calls """

def post(self, request, path):
""" Handles POST calls """


And I have a util class in my package like so:



class MyUtilClass:
""" Helps out with stuff """



def some_method(self, path):
print('I will now do things to the path: ', path)



Now, I would like to inject an instance of some other class that does some task that it's supposed to into my view. Something like this:



class MyAPIView(APIView):
""" My API """

_some_util_instance = None # How to inject this?

def __init__(self, util_instance):
self._some_util_instance = util_instance # Is this the right way?

def get(self, request, path):
""" Handles GET calls """
self._some_util_instance.some_method(path) # This is why I want this object injected.

def post(self, request, path):
""" Handles POST calls """


What is the best way to inject such an instance into my views class?



I could not find much about this in the documentation. I am familiar with using DI and IoC Containers. However, I am not sure how Django Rest Framework handles all of that.










share|improve this question























  • You need to be a bit more specific. Where is this instance coming from, and what are you intending to do with it?
    – Daniel Roseman
    Nov 9 at 22:45










  • added some context
    – ritratt
    Nov 9 at 22:54










  • That doesn't really help. Why would that be a class? Why would you need to inject it? Why wouldn't it simply be a function that you import and call?
    – Daniel Roseman
    Nov 9 at 22:57










  • It is a class because it has multiple implementations. It needs to be injected to make testing easier. It cannot be a function because there are multiple implementations.
    – ritratt
    Nov 9 at 23:04














up vote
0
down vote

favorite












I am kinda new to Django Rest Framework.



I have a views.py that looks something like this:



class MyAPIView(APIView):
""" My API """

def get(self, request, path):
""" Handles GET calls """

def post(self, request, path):
""" Handles POST calls """


And I have a util class in my package like so:



class MyUtilClass:
""" Helps out with stuff """



def some_method(self, path):
print('I will now do things to the path: ', path)



Now, I would like to inject an instance of some other class that does some task that it's supposed to into my view. Something like this:



class MyAPIView(APIView):
""" My API """

_some_util_instance = None # How to inject this?

def __init__(self, util_instance):
self._some_util_instance = util_instance # Is this the right way?

def get(self, request, path):
""" Handles GET calls """
self._some_util_instance.some_method(path) # This is why I want this object injected.

def post(self, request, path):
""" Handles POST calls """


What is the best way to inject such an instance into my views class?



I could not find much about this in the documentation. I am familiar with using DI and IoC Containers. However, I am not sure how Django Rest Framework handles all of that.










share|improve this question























  • You need to be a bit more specific. Where is this instance coming from, and what are you intending to do with it?
    – Daniel Roseman
    Nov 9 at 22:45










  • added some context
    – ritratt
    Nov 9 at 22:54










  • That doesn't really help. Why would that be a class? Why would you need to inject it? Why wouldn't it simply be a function that you import and call?
    – Daniel Roseman
    Nov 9 at 22:57










  • It is a class because it has multiple implementations. It needs to be injected to make testing easier. It cannot be a function because there are multiple implementations.
    – ritratt
    Nov 9 at 23:04












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I am kinda new to Django Rest Framework.



I have a views.py that looks something like this:



class MyAPIView(APIView):
""" My API """

def get(self, request, path):
""" Handles GET calls """

def post(self, request, path):
""" Handles POST calls """


And I have a util class in my package like so:



class MyUtilClass:
""" Helps out with stuff """



def some_method(self, path):
print('I will now do things to the path: ', path)



Now, I would like to inject an instance of some other class that does some task that it's supposed to into my view. Something like this:



class MyAPIView(APIView):
""" My API """

_some_util_instance = None # How to inject this?

def __init__(self, util_instance):
self._some_util_instance = util_instance # Is this the right way?

def get(self, request, path):
""" Handles GET calls """
self._some_util_instance.some_method(path) # This is why I want this object injected.

def post(self, request, path):
""" Handles POST calls """


What is the best way to inject such an instance into my views class?



I could not find much about this in the documentation. I am familiar with using DI and IoC Containers. However, I am not sure how Django Rest Framework handles all of that.










share|improve this question















I am kinda new to Django Rest Framework.



I have a views.py that looks something like this:



class MyAPIView(APIView):
""" My API """

def get(self, request, path):
""" Handles GET calls """

def post(self, request, path):
""" Handles POST calls """


And I have a util class in my package like so:



class MyUtilClass:
""" Helps out with stuff """



def some_method(self, path):
print('I will now do things to the path: ', path)



Now, I would like to inject an instance of some other class that does some task that it's supposed to into my view. Something like this:



class MyAPIView(APIView):
""" My API """

_some_util_instance = None # How to inject this?

def __init__(self, util_instance):
self._some_util_instance = util_instance # Is this the right way?

def get(self, request, path):
""" Handles GET calls """
self._some_util_instance.some_method(path) # This is why I want this object injected.

def post(self, request, path):
""" Handles POST calls """


What is the best way to inject such an instance into my views class?



I could not find much about this in the documentation. I am familiar with using DI and IoC Containers. However, I am not sure how Django Rest Framework handles all of that.







python django dependency-injection django-rest-framework inversion-of-control






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 9 at 22:54

























asked Nov 9 at 22:41









ritratt

73531327




73531327











  • You need to be a bit more specific. Where is this instance coming from, and what are you intending to do with it?
    – Daniel Roseman
    Nov 9 at 22:45










  • added some context
    – ritratt
    Nov 9 at 22:54










  • That doesn't really help. Why would that be a class? Why would you need to inject it? Why wouldn't it simply be a function that you import and call?
    – Daniel Roseman
    Nov 9 at 22:57










  • It is a class because it has multiple implementations. It needs to be injected to make testing easier. It cannot be a function because there are multiple implementations.
    – ritratt
    Nov 9 at 23:04
















  • You need to be a bit more specific. Where is this instance coming from, and what are you intending to do with it?
    – Daniel Roseman
    Nov 9 at 22:45










  • added some context
    – ritratt
    Nov 9 at 22:54










  • That doesn't really help. Why would that be a class? Why would you need to inject it? Why wouldn't it simply be a function that you import and call?
    – Daniel Roseman
    Nov 9 at 22:57










  • It is a class because it has multiple implementations. It needs to be injected to make testing easier. It cannot be a function because there are multiple implementations.
    – ritratt
    Nov 9 at 23:04















You need to be a bit more specific. Where is this instance coming from, and what are you intending to do with it?
– Daniel Roseman
Nov 9 at 22:45




You need to be a bit more specific. Where is this instance coming from, and what are you intending to do with it?
– Daniel Roseman
Nov 9 at 22:45












added some context
– ritratt
Nov 9 at 22:54




added some context
– ritratt
Nov 9 at 22:54












That doesn't really help. Why would that be a class? Why would you need to inject it? Why wouldn't it simply be a function that you import and call?
– Daniel Roseman
Nov 9 at 22:57




That doesn't really help. Why would that be a class? Why would you need to inject it? Why wouldn't it simply be a function that you import and call?
– Daniel Roseman
Nov 9 at 22:57












It is a class because it has multiple implementations. It needs to be injected to make testing easier. It cannot be a function because there are multiple implementations.
– ritratt
Nov 9 at 23:04




It is a class because it has multiple implementations. It needs to be injected to make testing easier. It cannot be a function because there are multiple implementations.
– ritratt
Nov 9 at 23:04












1 Answer
1






active

oldest

votes

















up vote
2
down vote













class MyAPIView(APIView):
""" My API """

_some_util_instance = MyUtilClass()


Or



class MyAPIView(APIView):
""" My API """

def __init__(self, *args, **kwargs):
self._some_util_instance = MyUtilClass()
super().__init__(self, *args, **kwargs)


Or



MyAPIView.as_view(
_some_util_instance=MyUtilClass()
)

class MyAPIView(APIView):
""" My API """

_some_util_instance = None


Or



don't use a class as a container for your utility functions, just define them as module-level functions. This is my preferred approach.



Or



Use static/class methods



class MyUtilClass:
""" Helps out with stuff """

@classmethod
def some_method(cls, path):
print('I will now do things to the path: ', path)


Then you can simply call MyUtilClass.some_method(path) in the view without creating an instance of MyUtilityClass






share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53234190%2fhow-to-inject-an-attribute-or-an-object-into-a-view-in-django-rest-framework%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    2
    down vote













    class MyAPIView(APIView):
    """ My API """

    _some_util_instance = MyUtilClass()


    Or



    class MyAPIView(APIView):
    """ My API """

    def __init__(self, *args, **kwargs):
    self._some_util_instance = MyUtilClass()
    super().__init__(self, *args, **kwargs)


    Or



    MyAPIView.as_view(
    _some_util_instance=MyUtilClass()
    )

    class MyAPIView(APIView):
    """ My API """

    _some_util_instance = None


    Or



    don't use a class as a container for your utility functions, just define them as module-level functions. This is my preferred approach.



    Or



    Use static/class methods



    class MyUtilClass:
    """ Helps out with stuff """

    @classmethod
    def some_method(cls, path):
    print('I will now do things to the path: ', path)


    Then you can simply call MyUtilClass.some_method(path) in the view without creating an instance of MyUtilityClass






    share|improve this answer
























      up vote
      2
      down vote













      class MyAPIView(APIView):
      """ My API """

      _some_util_instance = MyUtilClass()


      Or



      class MyAPIView(APIView):
      """ My API """

      def __init__(self, *args, **kwargs):
      self._some_util_instance = MyUtilClass()
      super().__init__(self, *args, **kwargs)


      Or



      MyAPIView.as_view(
      _some_util_instance=MyUtilClass()
      )

      class MyAPIView(APIView):
      """ My API """

      _some_util_instance = None


      Or



      don't use a class as a container for your utility functions, just define them as module-level functions. This is my preferred approach.



      Or



      Use static/class methods



      class MyUtilClass:
      """ Helps out with stuff """

      @classmethod
      def some_method(cls, path):
      print('I will now do things to the path: ', path)


      Then you can simply call MyUtilClass.some_method(path) in the view without creating an instance of MyUtilityClass






      share|improve this answer






















        up vote
        2
        down vote










        up vote
        2
        down vote









        class MyAPIView(APIView):
        """ My API """

        _some_util_instance = MyUtilClass()


        Or



        class MyAPIView(APIView):
        """ My API """

        def __init__(self, *args, **kwargs):
        self._some_util_instance = MyUtilClass()
        super().__init__(self, *args, **kwargs)


        Or



        MyAPIView.as_view(
        _some_util_instance=MyUtilClass()
        )

        class MyAPIView(APIView):
        """ My API """

        _some_util_instance = None


        Or



        don't use a class as a container for your utility functions, just define them as module-level functions. This is my preferred approach.



        Or



        Use static/class methods



        class MyUtilClass:
        """ Helps out with stuff """

        @classmethod
        def some_method(cls, path):
        print('I will now do things to the path: ', path)


        Then you can simply call MyUtilClass.some_method(path) in the view without creating an instance of MyUtilityClass






        share|improve this answer












        class MyAPIView(APIView):
        """ My API """

        _some_util_instance = MyUtilClass()


        Or



        class MyAPIView(APIView):
        """ My API """

        def __init__(self, *args, **kwargs):
        self._some_util_instance = MyUtilClass()
        super().__init__(self, *args, **kwargs)


        Or



        MyAPIView.as_view(
        _some_util_instance=MyUtilClass()
        )

        class MyAPIView(APIView):
        """ My API """

        _some_util_instance = None


        Or



        don't use a class as a container for your utility functions, just define them as module-level functions. This is my preferred approach.



        Or



        Use static/class methods



        class MyUtilClass:
        """ Helps out with stuff """

        @classmethod
        def some_method(cls, path):
        print('I will now do things to the path: ', path)


        Then you can simply call MyUtilClass.some_method(path) in the view without creating an instance of MyUtilityClass







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 10 at 1:08









        rikAtee

        4,61042855




        4,61042855



























             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53234190%2fhow-to-inject-an-attribute-or-an-object-into-a-view-in-django-rest-framework%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

            Syphilis

            Darth Vader #20