Create classes at runtnime

Peter Otten __peter__ at web.de
Sun Feb 6 13:31:16 CET 2011


Marc Aymerich wrote:

> On Feb 5, 1:06 pm, Marc Aymerich <glicer... at gmail.com> wrote:
>> Thank you all for the answers!
>>
>> I'll try to give you the context in which I need to generate classes
>> like this.
>>
>> I'm developing a reusable control panel for an ISP. I have several
>> modules (VirtualUser, SystemUser, VPS, VirtualHost, ...) and they all
>> share the fact that you can have limits on resource consumption. for
>> example.
>>
>> VPS: has limits on swap, memory, cpu and disk.
>> SystemUser: has limits on disk and traffic.
>>
>> As all modules share this property of being limited I have decided to
>> split the limit functionality in a separate module (called resources).
>> Resources are associated dinamically with (vps, systemuser ...)
>> through a Monitor class. So it's up to you decide what limits you are
>> interested to put in the VPS or in the SystemUser ...
>>
>> So when you attach the "disk limit" to SystemUser model is necessary
>> to create a web form for SystemUser a bit different than if you decide
>> to have disk and traffic limits. That is what my posted code is
>> supposed to do.
>>
>> Do you think that I am on the wrong way designing the control panel
>> like this?
>>
>> Btw, I've seen several interesting ideas to create the class
>> dinamically (with class factorys, MetaClass, dictionaries ..), but I
>> have not yet clear whether this will be usefull for create the
>> __init__ function at runtime too. Any clue on this?
>>
> 
> this seems to work :)
> 
> def makeLimitForm(name, monitors, _model):
> 
>     class Meta:
>         model = _model
>     dct = { 'Meta': Meta }
> 
>     for monitor in monitors:
>         field_name = monitor.resource + "_limit"
>         dct[field_name] = forms.CharField(max_length=100,
> initial=monitor.default_limit)
> 
>     def __init__(self, *args, **kwargs):
>         ModelForm.__init__(self, *args, **kwargs)
>         if 'instance' in kwargs:
>             for monitor in monitors:
>                 field_name = monitor.resource + "_limit"
>                 print monitor
>                 self.fields[field_name].initial =
> kwargs['instance'].monitoring.filter(monitor=monitor)[0].current
> 
>     dct['__init__'] = __init__
> 
>     return type(name,(ModelForm,),dct)

I've looked around to see whether Django offers an API for your usecase, but 
only found

http://code.djangoproject.com/wiki/DynamicModels

which seems to describe what you are already doing.



More information about the Python-list mailing list