python-injector / flask_injector

Adds Injector support to Flask.
BSD 3-Clause "New" or "Revised" License
278 stars 43 forks source link

Any examples for Flask-RestPlus Resource constructors ? #40

Open AbdoDabbas opened 5 years ago

AbdoDabbas commented 5 years ago

Hi, I'm completely new to python world so excuse my lack of knowledge.

I read in the documentation that this also supports Flask-RestPlus Resource constructors, even though I could find neither here or on the internet any decent example that uses Flask-RestPlus with this library.

I tried my self and what I reached is that I need to consider the API resource like any other class and configure it with the binder, is this the correct way to do it?, because in the examples (while using with bare Flask) there was no need to configure the routes, as they are already a function, not a class, I don't know if this is the reason.

jstasiak commented 5 years ago

There's an example piece of code in the test suite, I hope this helps.

AbdoDabbas commented 5 years ago

Actually this example is ver simplified, and I'm trying the same but for some reason, it's failing, here's a question I posted on Stackoverflow if you can have a look at: https://stackoverflow.com/questions/57806445/using-flask-injector-with-flask-restplus-causes-an-error-when-calling-the-api-re

AbdoDabbas commented 5 years ago

Strange thing, when the resource's constructor is written like this: def __init__(self, some_input: type_of_input, **kwargs): It works, but if I removed the **kwargs it will not, I think Flask-Injector is passing the api variable through kwargs for some reason. Even if I didn't call the super().__init__(*args, **kwargs) it still works.

What's the reason that I have to add kwargs when using the injector but not when I don't use it?

jstasiak commented 5 years ago

This is the signature of Flask-RESTPlus's Resource constructor:

    def __init__(self, api=None, *args, **kwargs):
        # ...

(source)

The api parameter is required in order for Resource to operate correctly. flask-injector hardcodes this knowledge and passes api behind the scenes.

If you want you can simplify your constructor to

def __init__(self, some_input: type_of_input, api):
    super().__init__(api)
    # ...

But that's as far as the simplifications will go right now.

MariposaGentil commented 3 years ago

dependency_injector needs that constructor for calling itself, I've been diving into the documentation and no one mentions that this is a thing to consider, maybe should be included.