使用Python中HTML中另存为变量的数据 [英] Using data saved as a variable in HTML from Python

查看:51
本文介绍了使用Python中HTML中另存为变量的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将在python文件中定义的变量传递到同一目录中的html文件并在'script'标签中使用?

简介: 我创建了一个flask网站,该网站从数据库中提取数据,并使用它在chartjs中创建折线图. Flask使用jijna来管理模板.数据库中的数据已经过规范化,因此可以由图表脚本读取(标签在列表中,数据作为元组).到目前为止,我已经制作了路由,以便可以访问每个页面并将该值传递到return_template参数中,如下所示:

Synopsis: Im producing a flask website that pulls data from a database and uses it to create a line chart in chartjs. Flask uses jijna to manage templates. The data in the databse has been normalised so that it can be read by the chart script (label is in a list, data as a tuple). So far I have produced routes so that each page can be accessed and passed the value into the return_template parameter as shown here:

@app.route('/room2')
def room2():
    return render_template('room2.html', title = 'Room2', time = newLabel, count = newData )

带有要调用的房间的html以及可以在此处访问的标题:

with the html for the room being called along with the title which is accessed here:

{% if title %}
    <title>Website title - {{ title }}</title>
{% else%}
    <title>Website</title>
{% endif %}

该图表是在html文件中生成的,我想获取数据(时间和计数)并在脚本中使用它,就像使用标题一样.但是,chart.js的脚本不使用{{}}(无论如何本质上是一个打印功能).到目前为止,我已经设法将所需的数据输入到所需的html文件中,通过将数据打印到页面本身即可证明这一点,但是我不确定如何将其转换为可由chartjs使用的变量.

The chart is being generated in the html file, and I want to take the data (time and count) and use it in the script the same way the title is used. However the script for chart.js doesnt take {{ }} (which is essentially a print function anyway). So far ive managed to get the data i want INTO the required html file, which is proven by the data being printed out onto the page itself but im not sure how to translate it into a variable to be used by chartjs.

有什么建议吗? (注意:使用这样的路由可能是错误的起点,但这是合乎逻辑的,并且除了逻辑之外没有产生任何错误)

Any suggestions? (NOTE: using routes like this may be the wrong starting point but it's one that makes logical sense and hasn't produced any errors beside logical)

文件:

  • data.py:从数据库获取信息并将其转换为两个变量;
label = ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00']
data = ['4,7,2,3,9,9,5]

  • routes.py:保存到所有页面的路由,
  • layout.html:保存网站的总体html代码
  • room.html:保存图形,从布局扩展
  • 推荐答案

    对于尝试将Flask和ChartJS放在一起的初学者,一种常见的方法似乎是编写使用循环输出Javascript或手动使用Jinja表达式的Jinja代码.在JS中.这可能很快成为维护的噩梦.

    For beginners who try to put Flask and ChartJS together, a common approach seems to be to write Jinja code which uses loops to output Javascript, or manually uses Jinja expressions within the JS. This can quick become a maintenence nightmare.

    这是我的方法,可让您定义要在Python中绘制的数据,使用一些最小的JS在画布中放置画布,然后使用Javascript Fetch API动态更新图表.

    Here's my approach which lets you define the data you want charted in Python, place a canvas in your template with some minimal JS, then dynamically update the chart using the Javascript Fetch API.

    您可以克隆存储库 flask-chartjs .

    您可以使用一种方法来绘制包含图表的页面:

    You can have one route which renders the page containing the chart:

    @app.route('/')
    def index():
        return render_template('index.html', CHART_ENDPOINT = url_for('data'))
    

    在这种情况下,

    CHART_ENDPOINT将是/data,它对应于另一个返回JSON的路由.我还有一个帮助程序功能,可以将纪元时间转换为与ISO 8601兼容的格式,并且可以使用矩.

    CHART_ENDPOINT in this case will be /data which corresponds to another route which returns the JSON. I also have a helper function which converts epoch times to a ISO 8601 compatible format, which works with moment.

    import datetime as DT
    def conv(epoch):
        return DT.datetime.utcfromtimestamp(epoch).isoformat()
    
    @app.route('/data')
    def data():
        d = {'datasets':
                [
                    {'title': 'From Dict',
                     'data': [ {'x': conv(1588745371), 'y': 400},
                               {'x': conv(1588845371), 'y': 500},
                               {'x': conv(1588946171), 'y': 800} ]
                    },
                ]
             }
    
        return jsonify(d)
    

    现在在模板中,您可以使用data-endpoint属性放置图表的canvas元素:

    Now in the template you can place the chart's canvas element with data-endpoint attribute:

    <canvas id="canvas" data-endpoint='{{CHART_ENDPOINT}}'></canvas>
    

    然后,我实现了两个JS函数,它们可以在同一模板中创建图表,并从提供的端点加载数据:

    Then I've implemented two JS functions which in that same template allow you to create the chart, and load the data from the provided endpoint:

    <script type='text/javascript'>
        var ctx = document.getElementById('canvas');
    
        myChart = create_chart(ctx);
    
        window.onload = function () { 
          load_data(myChart)
        };
    </script>
    

    create_chart函数data-endpoint属性获取端点,并在将其分配给该图表之前将其添加到config对象(信用):

    In the create_chart function the endpoint is obtained from the data-endpoint attrib, and added to the config object before it is assigned to that chart (credit):

    config.endpoint = ctx.dataset.endpoint;
    return new Chart(ctx.getContext('2d'), config);
    

    然后,load_data函数从chart.config.endpoint访问端点,这意味着它始终为所提供的图表获取正确的数据.

    The load_data function then accesses the endpoint from chart.config.endpoint meaning it always grabs the correct data for the provided chart.

    您还可以设置时间单位创建图表时:

    You can also set the time units when creating the chart:

    myChart = create_chart(ctx, 'hour') # defaults to 'day'
    

    我发现这通常需要根据您的数据范围进行调整.

    I've found this usually needs to be tweaked depending on your data range.

    create_chart函数中修改该代码以与端点相同的方式获取代码将是微不足道的.如果属性为data-unit,则类似于config.options.scales.xAxes[0].time.unit = ctx.datasets.unit.也可以对其他变量执行此操作.

    It would be trivial to modify that code to obtain this in the same manner as the endpoint, within the create_chart function. Something like config.options.scales.xAxes[0].time.unit = ctx.datasets.unit if the attribute was data-unit. This could also be done for other variables.

    您还可以在加载数据时从前端传递一个字符串(例如dynamicChart是使用上述方法创建的另一个图表):

    You can also pass a string from the frontend when loading data (say dynamicChart is another chart, created with the method above):

    load_data(dynamicChart, 'query_string')
    

    这将使烧瓶中的'query_string'用作request.args.get('q')

    如果要实现(例如)将字符串发送到后端的文本输入字段,这将很有用,因此后端可以以某种方式对其进行处理并返回在图表上呈现的自定义数据集.回购中的/dynamic路线对此进行了演示.

    This is useful if you want to implement (for example) a text input field which sends the string to the backend, so the backend can process it somehow and return a customised dataset which is rendered on the chart. The /dynamic route in the repo kind of demonstrates this.

    这是呈现的样子:

    如您所见,那么在一页上也可以有多个图表.

    As you can see it's possible then to have multiple charts on one page also.

    这篇关于使用Python中HTML中另存为变量的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆