0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DBから関数名を読みだして動的に実行する

Posted at

フォルダ構成

project
  |
 ├ __init__.py
 ├ apps.py
 ├ models.py
 ├ routes.py
 ├ views.py

Modelをつくる

まずはmodels.pyに関数リストをあらわすクラスを規定します。

models.py
from django.db import models
from django.db.models.signals import post_save

class FuncList:

    func_id = models.CharField(max_length=50)
    callback = models.CharField(max_length=50)

    def get_func_id(self):
        return self.func_id

    def set_func_id(self, func_id):
        self.func_id = func_id
        self.save()

    def get_callback(self):
        return self.callback

    def set_callback(self, callback):
        self.callback = callback
        self.save()

DBへの保存/読み出しと動的実行

views.py
# DBへの保存
def save_function(**kwargs):

    func_list = FuncList()

    func_list.set_func_id(kwargs['func_id'])
    func_list.set_callback(kwargs['callback'])

    return

# 動的実行
def dynamic_execution(arg1, arg2):

    # DBから読みだした関数を実行する関数
    def execution_handler(func, **kwargs):
        return func(**kwargs)

    # DBから関数リスト取得
    func_list = FuncList.objects.all()

    for i in range(len(func_list)):
        # 取得した関数を順番に実行
        result = execution_handler(func=eval(func_list[i].callback),
            arg1=arg1, arg2=arg2)

    return result

あとがき

言葉足らずでしたが見に来てくださりありがとうございました。
本記事で不明な点は以下のサイトなどで補完できます。・・・多分

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?