0

I am working on a Django Project, and I want the User to be able to add the code in the .py file. Well, I have .py file that contains some code, and in the mid of code I have some lines of code that specify some rules for Fuzzy Logic Algorithm, such as below:

 ...
rule1 = scikit-fuzzy.control.Rule(input1["bad"] & input2["bad"] & input3["bad"] & input4["bad"] & input5["average"], output["poor"])
 ...

So, I have total 243 lines of codes (in other words rules) like the above centered between some code (that is above it and below it there some other code). Now, I want Admin to be able to edit and update these lines of codes in a way that, using Forms I will take the inputs from the Admin (such as: 'good', 'bad', 'average', 'bad', 'good', 'poor', and I want the system to create a new line of code taking these strings as inputs.

If admin enters: 'good', 'bad', 'average', 'bad', 'good', 'poor', I want the .py to have a new line after the 243r line which should be like this:

rule243 = #
rule244 = scikit-fuzzy.control.Rule(input1["good"] & input2["bad"] & input3["average"] & input4["bad"] & input5["good"], output["poor"]

Can anyone help me in this?

8
  • 1
    Why just do not keep the logic rules in the database?
    – Farhad
    May 16, 2020 at 19:01
  • Is that possible? Actually I have to use those rules next in the calculation function of Fuzzy Logic Algorithm. May 16, 2020 at 19:06
  • Also in Database, the rules will be stored as strings, not the line of code. May 16, 2020 at 19:10
  • You can store the data as you want, but still, it is possible to move the rules to the database, and make it more dynamic
    – Farhad
    May 16, 2020 at 19:13
  • Can a line of code (not string strung between quotes or double quotes) be stored in database? For instance, can we store a = 2 + 4 in database? May 16, 2020 at 19:14

1 Answer 1

0

Actually this should be doable, I've a solution in mind, Let's implement it

Take caution

  • This requires HIGH verification and because this is python code, You don't want to give the admin all the rights to execute ANY python code from the admin page. If the admin details gets hijacked, You're @#!$#ED.

Let's analyze the problem into smaller problems.

Big point

  • We want to execute code from admin page

Smaller points

  • We need to put multiple rules, and they are uncountable, A perfect job for a database model

  • We will think of the code as Rule object. we will think of the dictionary key as a RuleKey object. we will think of input or output as RuleType

  • In your case, input1['good'] is the same as RuleTypeX[RuleKey] where x is an Integer starting from 1.

  • We will think of the RuleKey as many-to-many relation with the Rule, The Rule can has many RuleKey objects and those RuleKey objects can exist in different Rule objects.

THING TO CONSIDER

  • Verification is very important, YOU DON'T WANT SOMEONE PASSING eval() IN YOUR CODE AND EXECUTE WHATEVER HE WANTS.

I've created this REGEXP to match your code

scikit-fuzzy\.control\.Rule\(\s?((input[0-9]+\[("|')(poor|good|average|bad|whatever)("|')\])\s?&?\s?)+,?\s?(output[0-9]*\[("|')(poor|good|average|bad|whatever)("|')\])+\s?\)

Took a lot of time lol, Tested on Regexr, This matches your code well, paste your code there and test to see, feel free to improve it, this is not the main focus here.

class RuleKey(models.Model):
    class TYPES(models.IntegerChoices):
        INPUT = 0
        OUTPUT = 1

    content = models.CharField(max_length=10)
    type = models.IntegerField(choices=TYPES.choices)  # choices are of type Integer, the field must also be Integer

    def __str__(self):
        return self.content

content will contain any of ['poor', 'good', 'whatever'] and type will be 0 for Input and 1 for Output and I MEANT TO TYPE IT CAPITALIZED because we need to solve the caps problem too.

We have a function to check if the final code is valid before evaluating it.

def valid_python_code(code):
    if re.match(valid_code_pattern, code):
        return True

    return False

Don't use the stupid RegexValidator that django provides, It raises an Exception if it didn't match but IT RETURNS NONE IF IT MATCHES, makes no sense for me, or use it, whatever.

When we run code, We're 'executing' it and this is the formal word for running code.

class Rule(models.Model):
    keys = models.ManyToManyField('RuleKey', related_name='rules')
    wasExecutedBefore = models.BooleanField(default=False)  # ran before or no

    def execute(self):
        if self.wasExecutedBefore:
            return None

        input_keys = self.keys.filter(type=0)
        output_keys = self.keys.filter(type=1)

        """
        Can't use f-strings as we're evaluating genexps here, note the key.type, In a production environment
        This should be RuleKey.TYPES.INPUT or RuleKey.TYPES.OUTPUT, just swap the places of the classes, I'm lazy to do that
        """
        code = "scikit-fuzzy.control.Rule({inputs}, {outputs})".format(
            inputs=''.join(
                f"{key.get_type_display().lower()}{i + 1}['{key.content}']" for i, key in enumerate(input_keys) if
                key.type == 0),
            outputs=''.join(
                f"{key.get_type_display().lower()}{j + 1}['{key.content}']" for j, key in enumerate(output_keys) if
                key.type == 1))

        if valid_python_code(code):
            return eval(code)
        else:
            raise ValueError('Invalid code or missing libs or whatever.')

Lemme comment here the problems I tackled when implementing this.

  • RuleKey.TYPES is an IntegerChoices class, Django takes the attributes and capitalizes the first letter and returns it, Your code needs input and not Input , fortunately we have str.lower()
  • The second problem is that a regular for-in loop doesn't have a counter when looping objects other than range objects, We will use enumerate instead.
  • The third problem is that f-strings introduced in Python-3.6 (Not sure of 3.6) don't support GENEXPS inside, You have to use .format()
  • The fourth problem is that when using a GENEXP directly inside format instead of using ''.join(GENEXP), You'll print the lazy version of it i.e <generator object at 0x214312>
  • Don't try to use keys = keys.objects.all() and do this in one query, The problem you'll face will be related to the foor loop counter

  • Don't use RuleKey.type, this returns the integer, You need to call django's get_foo_display and in this case it's get_type_display()

Let's illustrate

I'll name my variables on the following format, class_type_content

keys = [key_1_poor, key_0_good, key_1_average]

let's loop and filter

for key in keys: # no count  
    pass

let's enumerate

for i, item in enumerate(keys):
    print(i) # prints index
    print(item) # prints object

now for the .all() part, If you tried to iterate .all(), You'll succeed, however, If your input started with input1, Your output will start with output2 and this is because both are in the same Queryset object.

Now, Add this to your admin page, perhaps as a button.

# admin.py

class RuleAdmin(admin.ModelAdmin):
    def response_change(self, request, rule_obj):
        if "execute" in request.POST:
            try:
                obj.execute() # execute (DONT IGNORE THE NOTES BELOW)
                obj.wasExecutedBefore = True 
                obj.save()
            except (ValueError, TypeError): # eval failed or execute
                pass

            return redirect(".")
        return super().response_change(request, obj)


admin.site.register(Rule, RuleAdmin) # register with admin

NOTE You need to import re and all the required libs like scikit and the ones needed for your code in your models.py.

Now in your app, I named my app core , create templates/admin/core/rule, this is on the following format. <app_name/templates/admin/app_name/model_name> all lowercase.

add a file called change_form.html

add this

{% extends 'admin/change_form.html' %}

{% block submit_buttons_bottom %}
    {{ block.super }}
    <div class="submit-row">
            <input type="submit" value="Execute the rule" name="execute">
    </div>
{% endblock %}

This creates a form that posts execute then we capture it in the model admin and if it exists, we execute the code.

I've written this dev.to article based on this topic

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.