javascript - 如何使用 Django 在 HTML 按钮上执行 file.py?

标签 javascript python html django

我的目标是单击我的 Django 网页上的 HTML 按钮,这将执行本地 python 脚本。

我正在创建一个本地 Web 应用程序作为项目的接口(interface)。这不会被托管,并且总是在我的本地机器上运行。我的项目使用 python 脚本运行(它针对我的项目执行大量测试)。我所需要的只是在我的 Web 界面中使用一个按钮来在我的机器上执行此脚本。

我有一个模板 index.html 整个网页所在的位置。我想我可能需要在按下按钮时调用某种形式的 View 函数?

How to execute python code by django html button?

这个问题提示:

def index(request):
    if request.method == 'GET':
        return render(request, 'yourapp/index.html', {'output': ''})
    elif request.method == 'POST':
        py_obj = mycode.test_code(10)
        return render(request, 'yourapp/output.html', {'output': py_obj.a})

我只是将其作为测试进行了尝试,但是当我转到 URL(位于相应的 views.py 中)时没有任何 react :
def runtest(request):
    print("Hello World")
    Popen(['gnome-terminal', '-e', 'echo "Hello World"'], stdout=PIPE)
    return

但是我不太明白这是否能达到我的要求,我很难理解答案的暗示。

当按下按钮时,我可以在 Django 框架的哪个位置指定对本地 python 脚本的调用?

(我对 Web 应用程序的经验非常有限,这只是一个简单的界面,带有一些按钮来运行测试)

最佳答案

您将要尝试做的是在单击按钮时提交表单。然后,您可以从脚本中导入要运行的函数并在 View 中调用它们。然后,您重定向到同一页面。

我希望这有帮助!

index.html

<form method="post">
    {% csrf_token %}
    <button type="submit" name="run_script">Run script</button>
</form>

View .py
if request.method == 'POST' and 'run_script' in request.POST:

    # import function to run
    from path_to_script import function_to_run

    # call function
    function_to_run() 

    # return user to required page
    return HttpResponseRedirect(reverse(app_name:view_name)

关于javascript - 如何使用 Django 在 HTML 按钮上执行 file.py?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54438473/

相关文章:

javascript - Android 版本无法在设备上运行?

javascript - 不用 Javascript 创建平滑的隐藏/显示动画

javascript - 如何使用 useEffect() 从 useReducer() 和 useContext() 状态管理设置中的 api 获取数据?

javascript - 如何在不损失性能的情况下不断移动 SVG 路径

防止 XSS 的 Javascript

python - 通过 ssh 验证文件是否存在

python - 如何将csv文件转换为字符级one-hot-encode矩阵?

javascript - 在外面点击如何恢复正常? [Javascript]

javascript - Angular.js 和 Google Analytics 内容实验

python - 在用户指定的时间内运行 Python 脚本