如何将python变量传递到我的模板HTML文件?

2024-09-22 16:35:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用django,我想学习如何将python脚本中生成的变量传递到模板html文件。问题是我的脚本是一个循环,我希望它在一段时间后更新此值,但是我无法通过从views.py进行渲染,就像我尝试渲染并将其传递到html时一样,它只是将脚本的所有输出都聚集在一起,然后呈现html文件,将它们全部放在我放在html文件中的一个python变量引用中。非常感谢您的帮助。谢谢 这是我到目前为止拥有的循环文件:

def SIVAResponse(audio):
    "speaks audio passed as argument"
    response ="SIVA: " + audio + "\n"
    if 'siva' or 'SIVA' in audio:
        audio = audio.replace("siva", "seeva")
        for line in audio.splitlines():
            os.system("say " + audio)

    else:
        for line in audio.splitlines():
            os.system("say " + audio)

def assistant(command):
    "if statements for executing commands"

    if 'end' in command:
        SIVAResponse("Have a nice day bro.")
        sys.exit()

    elif 'hello' in command:
        day_time = int(strftime('%H'))
        if day_time < 12:
            SIVAResponse('Hello Sir. Good morning')
        elif 12 <= day_time < 18:
            SIVAResponse('Hello Sir. Good afternoon')
        else:
            SIVAResponse('Hello Sir. Good evening')
    else:
        myCommand()

    SIVAResponse('Hi sup bro, My name is siva,what can i do for you?')

while True:
    myCommand()

以下是my views.py的外观:

def LoadSivaGUI(request):
    return render(request, 'SIVA/sivaGUI.html')


def StartAIbutton(request):

    run([sys.executable,"the path to my loop file"],shell=False,stdout=PIPE)
    return render(request, 'SIVA/sivaGUI.html')

Tags: 文件in脚本forifrequestdefhtml
2条回答

在返回模板页面之前,可以在views.py中使用:

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc): 
    print "Doing stuff..."
    # do your stuff
    s.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
s.run()

对于基于函数的视图,最简单的方法是通过以下字典在返回中添加所需的信息:

def LoadSivaGUI(request):
    your_data = some_function_to_get_your_data()
    return render(request, 'SIVA/sivaGUI.html' {'my_data': your_data})

相关问题 更多 >