flask_injector
flask_injector copied to clipboard
How to configure so that only parameters marked with `Inject[SomeType]` are injected?
Hi, I have been diving deep into the lib and can't stress enough how much of a great project this is!
I'm using flask_injector and Flask-Pydantic, however, they seem to be conflicting with each other. (EDIT: I don't think this is Pydantic-specific)
ie:
@webhooks_api.route("/my_webhook", methods=["POST"])
@pydantic_validate()
def my_webhook(body: WebhookContract):
...
In the code above, flask_injector seems to be taking priority and raising:
E injector.UnsatisfiedRequirement: core.domains.rest.webhooks has an unsatisfied requirement on WebhookContract
Any tips on how to configure things so that only parameters marked with Inject[SomeType]
are injected?
See: https://injector.readthedocs.io/en/latest/api.html#injector.Inject
Hey, that's a good question – that's not really supported at the moment and I think we need to make it configurable
Hey, that's a good question – that's not really supported at the moment and I think we need to make it configurable
Hey @jstasiak, I hope all is well. I'm planning to pick this up and contribute with a PR for it. Do you have any suggestions or advices here that you think might help me implement this new functionality? Thanks in advance!
Hey @jonathanmach, I imagine it'll be roughly like this:
In this piece of code https://github.com/python-injector/flask_injector/blob/004b9b52727e9699d23168a600c490ee5de7a395/flask_injector/init.py#L65
if hasattr(fun, '__call__') and not isinstance(fun, type):
try:
type_hints = get_type_hints(fun)
except (AttributeError, TypeError):
# Some callables aren't introspectable with get_type_hints,
# let's assume they don't have anything to inject. The exception
# types handled here are what I encountered so far.
# It used to be AttributeError, then https://github.com/python/typing/pull/314
# changed it to TypeError.
wrap_it = False
except NameError:
wrap_it = True
else:
type_hints.pop('return', None)
wrap_it = type_hints != {}
if wrap_it:
return wrap_fun(inject(fun), injector)
- Replace
get_type_hints()
withinjector.get_bindings()
to detect if we actually have anything to inject - Replace
inject(fun)
withfun
to stop assuming we want to inject everything by default
Hey there, any updates on this issue ? I came across the same problem and would be happy to help, if @jonathanmach hasn't been able to get to work on it yet.
I've tried @jstasiak suggestion, however it would require inject
decorator to be included for endpoint methods, was that an expected behaviour ?
Hey @raul-macedo-freire, all the updates we have on this are above. Can you clarify what do you mean by "it would require inject decorator to be included for endpoint methods"? An example would be great.