Search code examples
pythonhtmllistcherrypy

Cherrypy issue on updating list


I have a script that use CherryPy. The script is working well and the HTML page is ok. On the HTML page I'm showing the content of one list (is only an exercise for learning). Even this is working but If I try to put a background color based on the values in the list, starts the problem!

            class HelloWorld(object):
                @cherrypy.expose
                def index(self):

               for i in range(0, len(li)): 
                    status_bkg[i]=color_status(li)

color status is a little function that return 'green' if li[i]==1 'red' if is 0. Then I send this two lists to html file in this way:

template = loader.load('index.html')
title = "Exerc 2"
ctx = Context(title=title, li=li, status=bkg=status_bkg)
return template.generate(ctx).render('html', doctype='html')

Now the html file have this kind of structure:

     ...
     <tr py:for="i in len(li)">
                <td class="${status_bkg[i]}">${li[i]}</td>
     <tr>           

The two classes "green" and "red" are ok. The first time all shows perfectly. But when the python script start to add time to time randomly 0 or 1 to the list, the problem raise! The two lists have the same length but only "li" is updated, not status_bkg!

Where I'm wrong? Tell me if you need more code, I understand that I've simplify a little bit.

Thanks!


Solution

  • I see another typo in your code(just for those who might want to help):

    ctx = Context(title=title, li=li, status=bkg=status_bkg)
    

    needs to be:

    ctx = Context(title=title, li=li, status_bkg=status_bkg)
    

    I think the problem is in your for loop, li is never iterating. Assuming status_bkg is a list, I would change your for loop to:

    for i in li:
       status_bkg.append(color_status(i))
    

    That would make sure that each element in li had a corresponding status_bkg element.