【问题标题】:Cannot display values of dictionary on my Flask webpage in Python无法在 Python 中的 Flask 网页上显示字典的值
【发布时间】:2020-12-25 14:27:02
【问题描述】:

我正在尝试在我的烧瓶网页上显示字典中包含的值。我可以在终端上显示它,但我无法在网页上显示它。所以我的网页中有一个部分有一个图表,我试图在该图表上显示值。图表的 X 轴有特定的日期,而 Y 轴有一定的数值​​。 这是我的函数,它在我的终端上显示字典,但是在从我的 postgresQl 表中检索值时,它会引发错误。 我的函数

    def stats(self, application):
       
        '''
        In this section

        GET
        Graph : for the last 30 days the number of request (stack bars) and as line
        Tables: for each campaign the matrix with the winning for segment

        POST
        Add a new arm to  the DLP (to every single bandit)2
        '''

        if request.method == 'POST':
            new_url = request.form['site_url']

            self.add_arm(new_url)

        # table for each campaign
        self.tables = {}
        landing_req = Landing_request.query.all()
        for rows in landing_req:
            self.tables[rows.campaign_id] = rows.campaign_id

        # Graph structure
        self.graph = {}
        lr = Landing_request.query.all()
        for rows in lr:
            self.graph[rows.id] = rows.id
        application.logger.info(f'Campaign inside the system - {len(self.bandit_campaigns)}')

        # for every campaign
        for campaign in self.bandit_campaigns:

            # Return the structure of the features
            x_list = self.Feature_inst.x_feature_dict.items()

            # Then I return the Improvement and the status of the single features
            best_value, status_ele = self.bandit[campaign].return_status(x_list)

            # application.logger.info(f'status_ele - {status_ele}')

            status_ele_pure = {a: self._ranked_status(k) for a, k in status_ele.items()}

            # for every device
            for device in status_ele_pure.keys():

                # for every page
                for page in status_ele_pure[device].keys():

                    if campaign in self.pages.keys():

                        if page in self.pages[campaign][device].keys():

                            status_ele_pure[device][page]['impressions'] = self.pages[campaign][device][page][
                                'impressions']
                            status_ele_pure[device][page]['conversions'] = self.pages[campaign][device][page][
                                'conversions']
                            status_ele_pure[device][page]['rate'] = self.pages[campaign][device][page]['rate']
                        else:
                            status_ele_pure[device][page]['impressions'] = 0
                            status_ele_pure[device][page]['conversions'] = 0
                            status_ele_pure[device][page]['rate'] = 0

                    else:

                        status_ele_pure[device][page]['impressions'] = 0
                        status_ele_pure[device][page]['conversions'] = 0
                        status_ele_pure[device][page]['rate'] = 0

                        # I will save the best and the matrix

            self.tables[campaign] = status_ele_pure

        today = datetime.datetime.now()

        # for all the campaign
        for campaign_id in self.bandit_campaigns:

            if campaign_id not in self.graph.keys():
                # Graph
                self.graph[campaign_id] = {}

            # I print the last 30 days data
            for i_day in range(30):

                # Select the day id
                eventid_i = (today - timedelta(days=i_day)).strftime('%Y%m%d')

                # If it's not there I initialize the system
                if eventid_i not in self.graph[campaign_id].keys():
                    self.graph[campaign_id][eventid_i] = {}

                # If there is the data
                if eventid_i in self.selection[campaign_id].keys():

                    self.graph[campaign_id][eventid_i] = self.selection[campaign_id][eventid_i]

                else:
                    self.graph[campaign_id][eventid_i] = None

        application.logger.info(f'selection - {self.selection}')

        application.logger.info(f'graph - {self.graph}')

        application.logger.info(f'tables - {self.tables}')

这里是html部分

<tbody>
                            {% for key,value in tables.items()  %}
                            <tr>
                            <td class="element">{{key}}</td>
                             <td class="element">

                                    {% for key_page,value in value[0].items()  %}
                                 <div class="box"> 
    
             
                                    <div>Page {{structure[key_page]}}</div>
                                    <div>Rank: {{value['rank']}} </div>
                    <div>Impressions: {{value['impressions']}} </div>
                    <div>Conversions: {{value['conversions']}} </div>
                    <div>Conversion rate: {{'%0.2f' % value['rate']|float}}%</div>

                                </div>
                                    {% endfor %}

                    
                             </td>
                             <td class="element">
                                        {% for key_page,value in value[1].items()  %}
                                 <div class="box"> 

       
                                    <div>Page {{structure[key_page]}}</div> 
                                    <div>Rank: {{value['rank']}} </div>
                    <div>Impressions: {{value['impressions']}} </div>
                    <div>Conversions: {{value['conversions']}} </div>
                    <div>Conversion rate: {{'%0.2f' % value['rate']|float}}%</div>

                                </div>
                                    {% endfor %}


                             </td>
###rest of code

这会引发错误,例如:jinja2.exceptions.UndefinedError: str object has no element 0 我尝试了几种方法,但没有任何效果。 请帮帮我。谢谢!

【问题讨论】:

    标签: python python-3.x dictionary flask jinja2


    【解决方案1】:

    在我深入研究您的代码之前:我发现有点奇怪的是:

    ....
       {% for key,value in tables.items()  %}
       ....
          {% for key_page,value in value[0].items()  %}
          ....
    

    您似乎在两个循环中使用value 作为循环变量。第二次使用value 覆盖第一个循环的value 的内容,这样就修改了value 的内容。在我详细介绍之前,请排除 this 是您的错误的原因,因为它可能是。

    请将第二个 value 重命名为其他名称 - 例如value_page - 然后提供反馈。谢谢!

    【讨论】:

    • 好的。请提供一个带有“假”数据的工作示例,以便我们更仔细地研究这个问题。
    • 这是我可以在终端上打印的字典。我希望这些记录显示在图表上。 [2020-09-08 11:23:05,368] 引擎中的信息:表 - {'':'','B6BBB0CD00':'B6BBB0CD00','18060962':'18060962','24047646':'24047646'} [ 2020-09-08 11:31:12,448] 引擎中的信息:图 - {UUID('fda39ab8-de0e-11ea-8012-00e12901b102'): UUID('fda39ab8-de0e-11ea-8012-00e12901b102'), UUID( '3a259e14-ece2-11ea-abcf-00e12901b102'): UUID('3a259e14-ece2-11ea-abcf-00e12901b102')
    【解决方案2】:

    你的功能 定义统计() …… 返回...

    没有returnstatement

    考虑到有两个部分:

    • 后端(python)
    • 前端(html 和/或 javascript)

    考虑到这一点,您需要将信息从一个传递到另一个。

    通过return从后端到前端

    例如:

    @app.route('/')
    def index():
        return 'Hello world'
    

    @app.route('/')
    def index():
        return render_template('index.html', variable1 = 'animal')
    

    @app.route('/')
    def index():
        return render_template('index.html', variable2= {'key1': 'value1', 'key2': 'value2')
    
    

    然后你可以在index.html上读取像这样的变量值

    <!doctype html>
    <title>Hello from Flask</title>
    {% if variable2 %}
      <h1>Value of first element in dict {{ variable2['key1'] }}!</h1>
    {% else %}
      <h1>Variable2 is not defined </h1>
    {% endif %}
    

    从前端到后端:

    <form action="{{ url_for('blueprint_name.') }}" method="POST">
            <button name="filename" type="submit" value="">Generar plantilla</button>
        </form>
    

    【讨论】:

    • 我已经尝试过这些东西,但没有一个真正起作用,它给出的只是一个 jinja2.exceptions.UndefinedError: str object has no element 0
    • 该消息表明您正在尝试执行 [0],而您必须执行 ['key']。 [0] 适用于列表类型的对象。
    • 我也试过了,它给出了 jinja2.exceptions.UndefinedError: 'str object' has no attribute ''
    • @thegreat_one 你能用 return 语句和路由更新你的代码吗?
    猜你喜欢
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    相关资源
    最近更新 更多