ivankorobkov / python-inject

Python dependency injection
Apache License 2.0
672 stars 77 forks source link

AttributeError: '_AttributeInjection' object has no attribute 'returning_clause' with peewee ORM #49

Closed dimma837 closed 4 years ago

dimma837 commented 4 years ago

Hi, Ivan! Thank you for creating this library. But I have some difficulties using it with peewee ORM. Main setup:

import inject
from peewee import MySQLDatabase

database = MySQLDatabase(**config)

def injection(binder):
    binder.bind(MySQLDatabase, database)

inject.configure(injection)

models packet:

import inject
from peewee import *

class BaseModel(Model):
    class Meta:
        database = inject.attr(MySQLDatabase)

class User(BaseModel):
    id = CharField(primary_key=True)
    name = TextField(null=True)

    class Meta:
        table_name = 'users'

Then during insertion User.create(id='unique_id', name='John') I caught this:

Traceback (most recent call last):
  File "C:\Workspace\python\my_project\service.py", line 40, in track
    User.create(id='unique_id', name='John'):
  File "C:\Workspace\python\my_project\venv\lib\site-packages\peewee.py", line 6202, in insert
    return ModelInsert(cls, cls._normalize_data(__data, insert))
  File "C:\Workspace\python\my_project\venv\lib\site-packages\peewee.py", line 7120, in __init__
    if self.model._meta.database.returning_clause:
AttributeError: '_AttributeInjection' object has no attribute 'returning_clause'

It looks like _AttributeInjection container doesn't unwrap into MySQLDatabase instance. Can you help me? Is it my stupidity?

Enviroment:

ivankorobkov commented 4 years ago

Hi,

AttributeInjection implements the python descriptor protocol. See https://docs.python.org/3/howto/descriptor.html. It allows an object to specify the __get__() method which is invoked automatically on attribute access. AttributeInjection returns an injected dependency in this method.

It seems, peewee somehow breaks the default attribute access and does not call the descriptor __get__() method manually.

I think it's better to ask the peewee author directly to support descriptors as database attributes.

dimma837 commented 4 years ago

Thanks for your answer, I created an issue in peewee project.