Basically, I want to store python modules with a few simple functions in my database. My project runs on Django. I came across python_field, however, its buggy. I want to execute the code on the save method for the Model. What is the standard way to do this? Thanks.
-
1I think there's a larger question here. Why do you want to save code in a database?John Gordon– John Gordon2017-08-26 14:05:15 +00:00Commented Aug 26, 2017 at 14:05
-
1I can't judge ... since they are people writing javascript on server side.dani herrera– dani herrera2017-08-26 14:22:51 +00:00Commented Aug 26, 2017 at 14:22
Add a comment
|
1 Answer
I guess they are not a standard way to do it because it looks like an antipattern. Anyway, for academical purposes, you can try with:
from django.db import models
from python_field.fields import PythonCodeField
class MyModel(models.Model):
....
source = PythonCodeField(blank=True, null=True)
....
def save(self, *args, **kwargs):
codeObject = compile(self.source, '<string>', 'exec')
exec( codeObject ) #executing before regular save
super(MyModel, self).save(*args, **kwargs)
exec( codeObject ) #executing after regular save
4 Comments
Arpit Solanki
OP already said python_field's buggy so any other alternative would be good rather than this one
dani herrera
@ArpitSolanki, just focused on question. I also included disclaimer. OP ask to execute it on save method, here it is ... with a big disclaimer. OP don't ask for alternative method. You agree?
Arpit Solanki
I don't agree why he want to store the code in DB itself but answer is okay itself.
dani herrera
Nice! my answer is about how to do it, I do not judge whether that is good or bad. I disclaimed that for me looks like bad, but I don't know all the whole context :)