python 中的 exec() 函数未在 django 中执行

exec() function in python not executing in django

希望你们一切都好。 我想在 django 中使用 exec() 函数来执行从数据库中选取的字符串。 我编写的代码仅适用于 python 脚本,但不适用于 Django 视图。下面是我在 python 脚本中的代码,我在笔记本中是 运行。

ticker = 'AAPL'
title = 'f"hey {ticker} is a really doing good."'
exec('title = ' + title)
print(title)

但 Django 视图中的相同代码未执行。下面是 views.py.

中的代码
ticker = 'AAPL'
title = queryset.title #The title here is The {ticker} is not doing good.
exec('title = ' + title)

它没有给写答案,只是返回第一个标题,如下所示。

The {ticker} is not doing good. Thats is the {ticker} body.

如果谁有解决办法,请帮我想想办法。

使用str.format(…) [Python-doc]格式化字符串:

ticker = 'AAPL'
title = queryset.title<strong>.format(</strong>ticker=ticker<strong>)</strong>

使用execeval:它会导致不需要的side-effects因此不安全。

我找到了答案。 如果你想执行一个变量,那么使用上面的代码是:

ticker = 'AAPL'
title = queryset.title.format(ticker=ticker)

如果你想用很多值来执行整个字典。那么**是一个不错的选择。例如

dictionary = {'ticker': 'Example', 'website': 'example.com'}
queryset.title.format(**dictionary)