i'm trying make attributes related apis configurable (these unrelated drf attributes), it's more of meta data utilize own application. purpose, i'm creating app i'm calling apimanager
sole purpose of api management.
the way i'm imagining implemented discovering apis defined within drf , define modeladmin
class manage apis along attributes.
api discovery
approach 1: import list of defined urls in urls.py
, filter prefix (e.g. ^api) - don't since relies on convention , led circular imports.
approach 2: define apis in module/api/view/
folder , find classes defined in each python file - don't well.
approach 3: go through each module , find classes sublcasses of apiview
, define model relevant meta data, this:
class api(models.model): modules.companies.api.view import companies _apis = ( (x,x) x in (lambda m: [ m.__dict__[c] c in m.__dict__ if ( isinstance(m.__dict__[c], type) , m.__dict__[c].__module__ == m.__name__ ) ])(companies) if issubclass(x, apiview) ) api = models.charfield(max_length=256, choices=_apis) class meta: verbose_name = 'api' verbose_name_plural = 'apis'
ignore in-class import , companies
instance, these used testing purposes.
this approach works if go through each module have in application, feels bit hacky , feel there simpler, more elegant way of doing this.
how approach problem? how design api management app?
following @sthzg's comment, made registration-based approach works out pretty well.
registration.py:
def register_api(cls): try: # check membership api = api.objects.get( module=cls.__class__.__module__, name=cls.__class__.__name__, ) # update api except api.doesnotexist: # register api api = api( module=cls.__class__.__module__, name=cls.__class__.__name__, ) api.save()
models.py:
class api(models.model): module = models.charfield(max_length=256) name = models.charfield(max_length=128) def get_class(self): return locate('%s.%s' % (self.module, self.name)) class meta: verbose_name = 'api' verbose_name_plural = 'apis' unique_together = ('module', 'name') def __unicode__(self): return '%s' % self.name
and api want register:
class apimanagermember(object): def __init__(self): super(apimanagermember, self).__init__() register_api(self) class companyviewset(apimanagermember, viewsets.modelviewset): queryset = company.objects.all() serializer_class = companyserializer lookup_url_kwarg = 'company_id'
inheriting drf apis apimanagermember
automatically build list of apis. starting point building api catalog , can extended building bigger api management package.
Comments
Post a Comment