Django,JavaScript&Co:在html上打印python-fi上运行的变量

2024-04-26 04:33:13 发布

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

我写了一个简单的例子:我有一个函数x = 100*Math.random(),它每t = 1000 ms打印一个数字。好吧,这很管用。在

我的问题是:如何使用/调用外部python函数(例如x = counter.py)而不是x = 100*Math.random()

somepage.html

    ... 
    <script  src="{% static 'jquery-1.11.2.js' %}"></script>
    <script src="{% static 'js/contaBIS.js' %}"></script>
    <button type="button" class="btn btn-success" id="start"> START </button>
    <p id ="A"></p>
    <p id ="B"></p>
    ...

康塔比斯.js

^{pr2}$

计数器.py

import time
z = 0
def prova(z):


    while z < 10:
        time.sleep(1)
        z = z + 1
        print(z)      // I see z only on Eclipse console
    return z

好的,HERE我看到了如何调用外部函数,但不知道如何在html上查看它的值。我需要写另一个视图吗?怎样?!在

我看着print the value of a variable in Python/Django?,但对我不好。在


Tags: 函数pysrcidtimehtmljsscript
2条回答

好的I solved part of my issue改变一些事情。我发布了另一个问题来更具体,因为我不能删除这个问题。 我在这里引用它,希望它对像我这样刚开始学习django的人有用:

Clicking on a html button, I call views.stream_response which "activates" views.stream_response_generator which "activates" stream.py and return a StreamingHttpResponse and I see a progressive list every second up to n at /stream_response/:

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

stream.py

import time             
def streamx(n):
    list = []  
    x=0
    while len(list) < n:      
        x = x + 1
        time.sleep(1)
        list.append(x)
        yield "<div>%s</div>\n" % list
    return list

views.py

def stream_response(request):
    n = 10         #I would like to take this value from a FORM on html
    resp = StreamingHttpResponse( stream_response_generator(n))
    return resp    


def stream_response_generator(n):
    res = stream.streamx(n)
    return res

urls.py

...
url(r'^homepage/provadata/$', views.provadata),    
url(r'^stream_response/$', views.stream_response, name='stream_response'),
...

homepage/provadata.html

<a href="{% url 'stream_response' %}" class="btn btn-info" role="button" id="btnGo">GO</a>

浏览器不能在web服务器(Django运行的地方)上执行任何随机代码,它只能下载页面。在

我的第一个赌注是创建一个实际运行的Django视图计数器.py并将其输出呈现为浏览器可以处理的内容。在

在您的查看器页面上,您应该包含一个AJAX调用,该调用获取前面提到的视图的结果。在

但是,请注意计数器.py不存储任何状态信息,这意味着每次运行它时,都会得到相同的输出:

0
1
2
3
4
5
6
7
8
9

所有这些都在10秒钟内呈现出来,对于AJAX调用(实际上,对于任何页面加载)来说,这是非常糟糕的响应时间。在

相关问题 更多 >